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
How to select item/cell of UICollectionView from code
提问by Nikola Kirev
I have implemented a UICollectionView
in 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 UICollectionView
class 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 selected
property of the cell to YES
;
它只是将selected
单元格的属性设置为YES
;
回答by leviathan
回答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 :-)