2013-07-26 41 views
10

私はUICollectionViewを持っており、その上にかなり多くのUICollectionViewCellsがあります。タップすると、セルをUICollectionViewの中心にスクロールしたいと思います。私が懸念しているのは、最後のセルまたはトップセルをタップしても、コレクションビューの中央に移動する必要があるということです。タップされたときにUICollectionViewを中央に配置する方法は?

私はcontentInsetsとオフセットを設定しようとしましたが、動作していないようです。私は選択時にコンテンツのサイズを変更し、スクロールが始まるときにオリジナルに戻さなければならないと思います。

あなたが呼び出す必要があります後:

+0

私の編集した答えをチェックしてください、私はそれにいくつかの変更を加えました – Mikhail

答えて

26

設定contentInsetsは、最初と最後のセルの周りにいくつかの余分なスペースを与える必要があります

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

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

これをタップされたアイテムを適切にセンタリングすべきです。

EDIT

それは本当に奇妙だが、コレクションビューメソッドに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]; 
} 

それは私のために正常に動作します。

+0

感謝の作品は完璧です。 –

+0

Typo: 'UIEdgeInstetsMake'は' UIEdgeInsetsMake'でなければなりません。 –

+0

私は "UICollectionViewがセレクタsetContentInsetsを宣言するための目に見えないインターフェースを得る" – shim

9

このバグは、スクロールビューのcontentInsetUICollectionViewFlowLayoutの間の悪いやりとりによって引き起こされたようです。私のテストでは、collectionView.contentInsetではなくlayout.sectionInsetを設定することで問題が解決されました。

上記受け入れ答えに基づいて、私は回避策を排除し、変更しますが:

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

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

ミハイルの回避策を修正するすばらしい解決策。ありがとう! – jomafer

2

にあなたは中央の位置に選択(タップ)セルを配置するscrollToItemAtIndexPathメソッドを使用することができますUICollectionViewで

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

タップされたアイテムを表示するための画面をスクロールし、センタリングする垂直中心位置に対する

1

スウィフト3溶液:

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

これはcollectionView上または下のインセットを追加しません!

関連する問題