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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13859736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:32:35  来源:igfitidea点击:

How to select item/cell of UICollectionView from code

objective-ciosipaduicollectionviewuicollectionviewcell

提问by Nikola Kirev

I have implemented a UICollectionViewin my app. My problem is that I need to select (like if the user tapped on it) a cell programmatically. The method:

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

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

That is part of the UICollectionViewclass is not what i need to call, since this method does not call:

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

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

It just sets the selectedproperty of the cell to YES;

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

回答by leviathan

Yes, this is proper behaviour. Documentation for [selectItemAtIndexPath:animated:scrollPosition:]says:

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

This method does not cause any selection-related delegate methods to be called.

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

回答by Shirish Kumar

I am calling [self collectionView:yourView didSelectItemAtIndexPath:yourIndexPath]to programmatically select a cell. But in the method cell is always nil. This works perfectly well when user selects a cell.

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

回答by nopopon

First, you need to make the target cell visible, otherwise [yourCollectionView cellForItemAtIndexPath:yourIndexPath]always returns nil.

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