2016-07-15 8 views
7

Iが水平各セルは、ビュー/デバイスの画面のサイズを占め、1個のセルが一度に表示さUICollectionViewスクロール、ページ分割を有します。デバイスの回転で、セルが正しいサイズに移行する問題が発生していますが、セルの位置はオフになります。回転前リサイズUICollectionViewCells現在表示されているセル

回転後

Before Rotation

:回転に

After Rotation

、どのように私はきちんとコレクションビューのセルのサイズを変更するが、現在のセルが表示されたままになりますことを確認することができるだけでなく、 ?

私はこの問題を、カスタムフローレイアウトなしの非常に簡単な例にまで煮詰めました。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 
    return collectionView.frame.size 
} 

viewWillLayoutSubviewsの回転を処理するためにしよう:

override func viewWillLayoutSubviews() { 
    super.viewWillLayoutSubviews() 

    guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return } 

    flowLayout.itemSize = collectionView.frame.size 

    flowLayout.invalidateLayout() 
} 
collectionViewフレームのサイズへの細胞の大きさを設定

(コレクションビューは、ビューコントローラのサイズを保持しています)私はviewWillLayoutSubviewsinvalidateLayout()を呼び出す場合

実は、ここitemSizeを設定すると、レイアウトが再作成されたときにsizeForItemAtIndexPathが呼び出されるよう、必要はありません。

私も新しいitemSizeを設定した後、回転中に最初の可視セルにスクロール手動で試してみたが、それは何の改善を示しています

if let item = collectionView.indexPathsForVisibleItems().first { 
    collectionView.scrollToItemAtIndexPath(item, atScrollPosition: .CenteredHorizontally, animated: true) 
} 

答えて

7

あなたのUICollectionViewのオフセットので、あなたのビューでコンテンツを処理する必要がありますコントローラは機能をUIContentContainerプロトコルからオーバーライドしようとします:

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) 

    let offset = yourCollectionView?.contentOffset; 
    let width = yourCollectionView?.bounds.size.width; 

    let index  = round(offset!.x/width!); 
    let newOffset = CGPointMake(index * size.width, offset!.y); 

    yourCollectionView?.setContentOffset(newOffset, animated: false) 

    coordinator.animateAlongsideTransition({ (context) in 
     yourCollectionView?.reloadData() 
     yourCollectionView?.setContentOffset(newOffset, animated: false) 
    }, completion: nil) 
} 
関連する問題