2013-03-05 13 views
13

私はのviewDidLoadでUICollectionViewを最初に読み込んだ後に、項目を選択する方法は?

[self collectionView:myCollectionView didSelectItemAtIndexPath:selectedIndexPath]

とUICollectionViewCellの選択= YESを書き込もうとしました、そして、それは方法didSelectItemAtIndexPathを実施しなかったが、セルが選択されていません。

私はUICollectionViewCellサブクラスの(void)setSelected:(BOOL)selectedで選択された状態を書きました。ビューが読み込まれた後、手動選択機能が働きます。しかし、ビューの最初の読み込み後にいくつかのアイテムを自動的に選択させることはできませんでした。

そして私はでコードを書くことを試みた:すべてOKではない、

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

私はそれを最初に実行viewDidLoaddidSelectItemAtIndexPathを発見し、その後、cellForItemAtIndexPath、私が、細胞が存在していないの前にいることから、cellForItemAtIndexPath前に(私が知っている)indexPathのセルを取得could'tことのように思えます。では、最初にロードした後にUICollectionViewのアイテムを選択する方法は?

私の貧しい私の英語のために申し訳ありません。前もって感謝します。

答えて

11

わからない、あなたの質問が正しいだが、ここでは可能な解決策だ場合:

で例えばviewWillAppear:は、プログラム「selectItemAtIndexPath」を呼び出すと、関連するデリゲートメソッドを呼び出すことはありませんので、心の中で

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

ベアを行います。必要に応じてコードで呼び出す必要があります。

+2

ありがとうございました!私はそれを取り組んだ!私はいつも間違ったコードを使いました:[self collectionView:_tagsCollectionView didSelectItemAtIndexPath:selectedIndexPath]そしてselectItemAtIndexPathではなく、どこにでも置こうとしました。 – zgjie

+0

私のビューが読み込まれるとき、このメソッドは私のためにうまくいきます。しかし、私の見解では私は自動的に選択された親指を持っています – bashan

+0

そしてあなたの問題は何ですか?最初の質問は、ビューの最初の負荷に関するものでした。 – SAE

8
私の場合は

selectItemAtIndexPathreloadData後には効果がなかったので、私はperformBatchUpdatesの完了ブロックでそれを呼び出す必要がありました:

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

let indexPath = ... 

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

ありがとうございます。私はreloadDataの後にselectItemアクションを作成するのと同じ状況にありました。あなたの答えは私の問題を解決しました。 –

4

スウィフト3

あなたcollectionviewが作成され、このオーバーライド機能を実装。 Instagram storiesのようなセクション1の行が1つあるとします。

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)) 
     } 
    } 
関連する問題