我以编程方式设置了一个名为UICollectionViewCell
的自定义CheckCell
,如下所示:
[self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES];
if ([[self.myCollectionView cellForItemAtIndexPath:indexPath] isSelected]) {
NSLog(@"Selected");
}
NSLog(@"%i",[self.myCollectionView indexPathsForSelectedItems].count);
第一个NSLog打印“已选择”,让我相信IndexPath
处的单元格确实被选中。但是,第二个NSLog的结果为0.为什么所选单元格的索引没有添加到indexPathsForSelectedItems
?
答案 0 :(得分:8)
这是答案。
致电selectItemAtIndexPath
而非[self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES];
示例代码:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0] ;
[self.collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
if ([[self.collectionView cellForItemAtIndexPath:indexPath] isSelected]) {
NSLog(@"selected count %i",[self.collectionView indexPathsForSelectedItems].count);
}
<强>输出强>
selected count 1