Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 以编程方式将UICollectionViewCell设置为选中,但indexPathsForSelectedItems.count为0_Ios_Objective C_Uicollectionview_Uicollectionviewcell - Fatal编程技术网

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
。必须手动完成。