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



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

- (void)selectItemAtIndexPath:(NSIndexPath *)indexPath 
                     animated:(BOOL)animated 
               scrollPosition:(UICollectionViewScrollPosition)scrollPosition

那是UICollectionView类的一部分,不是我需要调用的,因为此方法不调用:

- (void)collectionView:(UICollectionView *)collectionView 
        didSelectItemAtIndexPath:(NSIndexPath *)indexPath

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

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

此方法不会导致任何与选择相关的委托方法 名叫。

我正在调用[self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath]以编程方式选择一个单元格。 但在方法中单元格始终为零。 当用户选择单元格时,这非常有效。

首先

,您需要使目标单元格可见,否则[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 :-) 

最新更新