2013-03-05 28 views
13

我試着寫如何在第一次加載後在UICollectionView中選擇一些項目?

[self collectionView:myCollectionView didSelectItemAtIndexPath:selectedIndexPath]

和UICollectionViewCell的選擇= YES在viewDidLoad中,才實現的方法didSelectItemAtIndexPath,但細胞無法選擇。

我在UICollectionViewCell子類的(void)setSelected:(BOOL)selected中編寫了選定的狀態。視圖加載後,手動選擇功能起作用。但是我不能讓它在視圖第一次加載後自動選擇一些項目。

我試着寫碼:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath,都不確定。

我發現它第一次運行viewDidLoaddidSelectItemAtIndexPath,然後cellForItemAtIndexPath,好像,我無法cellForItemAtIndexPath之前獲得的indexPath細胞(我知道),因爲在此之前,該小區是不存在的。那麼如何在第一次加載後在UICollectionView中選擇一些項目?

對不起,我英文很差。提前致謝。

回答

11

不知道,如果有你的問題是正確的,但這裏有一個可能的解決方案:

在如viewWillAppear:

[self.collectionView reloadData]; 
NSIndexPath *selection = [NSIndexPath indexPathForItem:THE_ITEM_TO_SELECT 
              inSection:THE_SECTION]; 
[self.collectionView selectItemAtIndexPath:selection 
            animated:YES 
          scrollPosition:UICollectionViewScrollPositionNone]; 

請記住,在調用「selectItemAtIndexPath」程序不調用相關的委託方法;如果你需要他們,你必須在代碼中給他們打電話。

+2

謝謝!我已經完成了!我總是使用錯誤的代碼:[self collectionView:_tagsCollectionView didSelectItemAtIndexPath:selectedIndexPath]並試圖將它放在任何地方,而不是selectItemAtIndexPath,因此總是不起作用。 – zgjie 2013-03-05 16:39:43

+0

當我的視圖加載時,這種方法對我很有幫助。但在我看來,我有拇指自動選擇 – bashan 2013-10-14 18:42:57

+0

什麼是你的問題?原來的問題是關於視圖的第一個負載。 – SAE 2013-10-14 23:04:11

8

在我的情況selectItemAtIndexPath沒有效果reloadData後,所以我不得不調用它的performBatchUpdates完成塊:

collectionView.dataSource = ... 
collectionView.delegate = ... 

let indexPath = ... 

collectionView.performBatchUpdates(nil) { _ in 
    collectionView.selectItemAtIndexPath(indexPath, animated: false, scrollPosition: .None) 
} 
+0

謝謝。我在reloadData之後做了selectItem動作。你的答案解決了我的問題。 – 2017-04-11 04:33:34

4

斯威夫特3

實現這種超越功能是您的CollectionView創建哪裏。 假設我們有1個第1行像Instagram的故事。

override func viewDidAppear(_ animated: Bool) { 
     // Auto Select First Item 
     self.myCollectionView.performBatchUpdates(nil) { _ in 
      self.myCollectionView.selectItem(at: IndexPath(item: 0, section: 0), animated: false, scrollPosition: [.centeredHorizontally]) 
      self.collectionView(self.myCollectionView, didSelectItemAt : IndexPath(item: 0, section: 0)) 
     } 
    } 
相關問題