2013-03-16 30 views
4

我編程設置了一個名爲CheckCell要選擇定製UICollectionViewCell如下:編程設置UICollectionViewCell作爲選擇,但indexPathsForSelectedItems.count是0

[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

self.myCollectionView和myCollectionView是相同的? (你正在使用兩種變體!) – Till 2013-03-16 02:03:21

+0

是的,他們是一樣的,抱歉編輯錯誤,我會更新問題。 – IkegawaTaro 2013-03-16 02:17:02

回答

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 
+0

確實有用 - 謝謝。奇怪的是,問題中的代碼不... – IkegawaTaro 2013-03-16 04:20:58

+2

請注意,這不會導致調用委託方法'didSelectItemAtIndexPath'。必須手動完成。 – shim 2016-06-16 14:12:17

相關問題