13

書いてみた

[self collectionView:myCollectionView didSelectItemAtIndexPath:selectedIndexPath]

UICollectionViewCell の selected=YES が viewDidLoad にあり、メソッドdidSelectItemAtIndexPathを実装しましたが、セルが選択されていません。

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

そして、私はコードを書き込もうとしました:

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

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath、すべてOKではありません。

私はそれが最初に実行されたことを発見しviewDidLoaddidSelectItemAtIndexPathその後、 (私が知っている)以前にセルが存在しなかったためcellForItemAtIndexPath、セルを取得できなかったようです。では、最初のロード後にいくつかのアイテムを選択する方法は?indexPathcellForItemAtIndexPathUICollectionView

私の下手な英語でごめんなさい。前もって感謝します。

4

3 に答える 3

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」を呼び出しても、関連するデリゲート メソッドは呼び出されないことに注意してください。それらが必要な場合は、コードで呼び出す必要があります。

于 2013-03-05T16:10:24.317 に答える
7

スイフト3

コレクションビューが作成される場所に、このオーバーライド関数を実装します。Instagramのストーリーのように、セクション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))
        }
    }
于 2017-05-06T16:17:33.230 に答える