Ios 以编程方式将UICollectionViewCell设置为选中,但indexPathsForSelectedItems.count为0
我以编程方式将名为Ios 以编程方式将UICollectionViewCell设置为选中,但indexPathsForSelectedItems.count为0,ios,objective-c,uicollectionview,uicollectionviewcell,Ios,Objective C,Uicollectionview,Uicollectionviewcell,我以编程方式将名为CheckCell的自定义UICollectionViewCell设置为选中,如下所示: [self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES]; if ([[self.myCollectionView cellForItemAtIndexPath:indexPath] isSelected]) { NSLog(@"Selected"); } NSLog(@"%i",[self
CheckCell
的自定义UICollectionViewCell
设置为选中,如下所示:
[self.myCollectionView cellForItemAtIndexPath:indexPath] setSelected:YES];
if ([[self.myCollectionView cellForItemAtIndexPath:indexPath] isSelected]) {
NSLog(@"Selected");
}
NSLog(@"%i",[self.myCollectionView indexPathsForSelectedItems].count);
第一个NSLog打印“Selected”,这让我相信indepath
中的单元格确实被选中了。但是,第二个NSLog的结果是0。为什么所选单元格的索引没有添加到indexPathsForSelectedItems
?以下是答案
调用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
self.myCollectionView和myCollectionView是否相同?(您正在使用两个变量!)是的,它们是相同的,很抱歉编辑错误,我将更新问题。请注意,这不会导致调用委托方法didSelectItemAtIndexPath
。必须手动完成。