问题描述
我创建了一个 UICollectionView,以便我可以将视图排列成整齐的列.我希望在宽度大于 500 像素的设备上有一列.
I've created a UICollectionView, so that I can arrange views into neat columns. I'd like there to be a single column on devices > 500 pixels wide.
为了实现这一点,我创建了这个函数:
In order to achieve this, I created this function:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let size = collectionView.frame.width
if (size > 500) {
return CGSize(width: (size/2) - 8, height: (size/2) - 8)
}
return CGSize(width: size, height: size)
}
这在第一次加载时按预期工作,但是当我旋转设备时,计算并不总是再次发生,并且视图并不总是按预期重绘.这是我旋转设备时的代码:
This works as expected on first load, however when I rotate the device, the calculation doesn't always happen again, and the views don't always redraw as expected. Here's my code for when the device is rotated:
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
collectionView.collectionViewLayout.invalidateLayout()
self.view.setNeedsDisplay()
}
我假设我忘记重绘某些东西,但我不确定是什么.非常感谢收到任何想法!
I'm assuming I've forgotten to redraw something, but I'm not sure what. Any ideas are very gratefully recieved!
推荐答案
您可以使用 viewWillLayoutSubviews
.这个问题应该会有所帮助,但每当视图控制器视图即将布局其子视图时,这都会被调用.
You might use viewWillLayoutSubviews
. This question should be helpful but this is bassically called whenever the view controller views is about to layout its subviews.
所以你的代码看起来像这样:
So your code will look like this:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
if UIInterfaceOrientationIsLandscape(UIApplication.sharedApplication().statusBarOrientation) {
//here you can do the logic for the cell size if phone is in landscape
} else {
//logic if not landscape
}
flowLayout.invalidateLayout()
}
这篇关于UICollectionView - 在设备旋转上调整单元格大小 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!