以编程方式将UICollectionViewCell设置为Selected但indexPathsForSelectedItems.count为0

时间:2013-03-16 02:01:02

标签: ios objective-c uicollectionview uicollectionviewcell

我以编程方式设置了一个名为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

1 个答案:

答案 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