Swift:Collection在旋转后查看更改布局

时间:2017-04-10 10:31:03

标签: ios swift uicollectionview

我有一个包含6个项目的集合视图,并希望以每行2个单元格和3行格式显示它们。以下代码很好地实现了iPhone格式的这个问题(从这个问题:Swift: Collection View not adjusting correctly to change in size)。

然而,在任何iPad上,视图布局最初是正确的,但如果屏幕旋转为横向然后回到纵向,则布局不完全适合视图,并且需要水平滚动才能看到第二个单元格(单元格宽度已经以某种方式增加意义,每行中的第二个单元被部分切断。)

override func viewDidLoad() {
 super.viewDidLoad()
 collectionView.dataSource = self
 collectionView.delegate = self

 flowLayout.scrollDirection = .horizontal
 flowLayout.minimumLineSpacing = 5
 flowLayout.minimumInteritemSpacing = 5
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return 6
}


override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
    self.collectionView.collectionViewLayout.invalidateLayout()
}


 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

     if UIDevice.current.orientation.isLandscape {
        let totalWidth = collectionView.frame.width 
        let totalHeight = collectionView.frame.height 

        let heightOfCell = totalHeight / 2
        let numberOfCellsPerRow = 1
        let widthOfCell = CGFloat(Int(totalWidth) / numberOfCellsPerRow)

        return CGSize(width: widthOfCell , height: heightOfCell)

    } else {
        let totalWidth = collectionView.frame.width 
        let totalHeight = collectionView.frame.height 
        let heightOfCell = (totalHeight / 3)

        let numberOfCellsPerRow = 2
        let widthOfCell = CGFloat(Int(totalWidth) / numberOfCellsPerRow)

        return CGSize(width: widthOfCell , height: heightOfCell)
    }
}

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, 5, 0, 5)
}

Before rotation After rotation

1 个答案:

答案 0 :(得分:0)

这里的问题似乎是,当' willRotate'时,视图的框架不会更新。被调用。相反,尝试'旋转'#39;或添加观察者' NSNotification.Name.UIDeviceOrientationDidChange'和选择器方法中的invalidateLayout集合。别忘了在deinit()上删除观察者。