web-dev-qa-db-ja.com

タップされたときにUICollectionViewを中央に配置するにはどうすればよいですか?

私はUICollectionViewを持っていて、かなりたくさんのUICollectionViewCellsがあります。タップしたときにセルをUICollectionViewの中央までスクロールしたい。私の懸念は、最後または一番上のセルをタップしても、コレクションビューの中央に移動する必要があることです。

contentInsetsとオフセットを設定しようとしましたが、機能しないようです。選択時にコンテンツサイズを変更し、スクロールが開始されたら元に戻す必要があると思います。

14

ContentInsetsを設定すると、最初と最後のセルの周囲にスペースが追加されます。

CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds);
[collectionView
  setContentInset:
   UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ];
  // nb, those are top-left-bottom-right

電話をかけた後:

[collectionView scrollToItemAtIndexPath:selectedItemPath
    atScrollPosition:UICollectionViewScrollPositionCenteredVertically
    animated:YES];

正しいスクロール位置を渡すことが重要です:UICollectionViewScrollPositionCenteredVertically

これにより、タップされたアイテムが適切に中央に配置されます。

[〜#〜]編集[〜#〜]

本当に奇妙ですが、UIEdgeInsetsをコレクションビューメソッドに設定した後、scrollToItemAtIndexPathが正しく機能しないため、いくつか変更を加えます。

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.frame);
    [collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];

    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    CGPoint offset = CGPointMake(0,  cell.center.y - collectionViewHeight / 2);
    [collectionView setContentOffset:offset animated:YES];
}

それは私にとってはうまくいきます。

29
Mikhail

Swiftタップしたアイテムを表示するために画面をスクロールして中央に配置するためのソリューション:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
  collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
}

これは、collectionViewの上または下に挿入図を追加しません!

11
budidino

このバグは、スクロールビューのcontentInsetUICollectionViewFlowLayoutの間の不適切な相互作用が原因であると思われます。私のテストでは、layout.sectionInsetではなくcollectionView.contentInsetを設定することで問題が解消されました。

上記の受け入れられた回答に基づいて、回避策を排除し、以下を変更します。

[collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];

[layout setSectionInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)];
10
humblehacker

scrollToItemAtIndexPathメソッドを使用して、選択した(タップした)セルをUICollectionViewの中央の位置に配置できます

[collectionView scrollToItemAtIndexPath:indexPath
                       atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally
                               animated:true];

垂直方向の中央位置にはUICollectionViewScrollPositionCenteredVerticallyを使用できます