5

我以编程方式设置了一个自定义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

4

1 回答 1

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
于 2013-03-16T03:38:54.533 回答