如何从代码中选择UICollectionView的项目/单元格

Nik*_*rev 6 objective-c ipad ios uicollectionview uicollectionviewcell

UICollectionView在我的应用程序中实现了一个.我的问题是我需要选择(如果用户点击它)一个单元格programmatically.方法:

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition
Run Code Online (Sandbox Code Playgroud)

这是UICollectionView类的一部分不是我需要调用的,因为这个方法不会调用:

- (void)collectionView:(UICollectionView *)collectionView 
        didSelectItemAtIndexPath:(NSIndexPath *)indexPath
Run Code Online (Sandbox Code Playgroud)

它只是将selected单元格的属性设置为YES;

lev*_*han 9

是的,这是正确的行为.文档[selectItemAtIndexPath:animated:scrollPosition:] :

此方法不会导致调用任何与选择相关的委托方法.


Shi*_*mar 8

我打电话[self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath]以编程方式选择一个单元格.但在方法中,单元格总是为零.当用户选择单元格时,这非常有效.

  • 或者在swift中你可以使用:`collectionView.delegate?.collectionView!(collectionView,didSelectItemAtIndexPath:someIndexPath)` (7认同)

nop*_*pon 7

首先,您需要使目标单元格可见,否则[yourCollectionView cellForItemAtIndexPath:yourIndexPath]始终返回nil.

// scroll to the cell
[yourCollectionView scrollToItemAtIndexPath:yourIndexPath
                           atScrollPosition:UICollectionViewScrollPositionBottom 
                                   animated:NO];

// call delegate method
[self collectionView:yourCollectionView didSelectItemAtIndexPath:yourIndexPath];

// now you have selected the cell and can do anything to it in the delegate method :-) 
Run Code Online (Sandbox Code Playgroud)