我有一個包含6個項目的集合視圖,並且希望以每行2格和3行格式顯示它們。下面的代碼很好地實現了iPhone格式的這個(從這個問題中獲得:Swift: Collection View not adjusting correctly to change in size)。Swift:Collection查看旋轉後更改佈局
但是,在任何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)
}
我無法重現您的問題 - 我嘗試複製並粘貼您的確切代碼,並且當我旋轉縱向 - >橫向 - >縱向時,它與開始時完全相同。你能否展示一些截圖來更清楚地說明發生了什麼? –
我已經添加了它們,這隻發生在iPad上,而不是iPhone –
您是否調整過故事板上的任何內容?這不是我用代碼向我的場景添加全新集合視圖後得到的佈局。 –