UICollectionView Rotation 旋转后布局不正确
UICollectionView Rotation incorrect layout after rotation
我有一个 UICollectionView,它恰好有 7 个单元格宽,中间没有填充。我通过添加没有中间或行间距的流布局并按如下方式计算宽度来完成此操作:
public func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
return CGSize(
width: self.frame.width / CGFloat(7),
height: self.frame.height - headerHeight
)
}
这在我的 iPhone 应用程序中非常有效
未启用旋转。在 iPad 上,当处于纵向模式时,这工作正常。
旋转时,首先应用程序不会重绘,我尝试使布局无效,但这并没有解决问题。我必须向下滚动,然后得到以下布局
当我点击一个单元格时,它会重新绘制,但添加了填充将第 7 个单元格向下推到另一行。
我希望重新绘制单元格,以便当应用程序在拆分视图中旋转或放大和缩小时,所有 7 个单元格都适合一行。我该如何正确处理?
将此添加到您的 UIViewController
class
它会在您更改设备方向时自动调整您的布局。
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let columnLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
columnLayout.invalidateLayout()
}
我有一个 UICollectionView,它恰好有 7 个单元格宽,中间没有填充。我通过添加没有中间或行间距的流布局并按如下方式计算宽度来完成此操作:
public func collectionView(
_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath
) -> CGSize {
return CGSize(
width: self.frame.width / CGFloat(7),
height: self.frame.height - headerHeight
)
}
这在我的 iPhone 应用程序中非常有效
未启用旋转。在 iPad 上,当处于纵向模式时,这工作正常。
旋转时,首先应用程序不会重绘,我尝试使布局无效,但这并没有解决问题。我必须向下滚动,然后得到以下布局
当我点击一个单元格时,它会重新绘制,但添加了填充将第 7 个单元格向下推到另一行。
我希望重新绘制单元格,以便当应用程序在拆分视图中旋转或放大和缩小时,所有 7 个单元格都适合一行。我该如何正确处理?
将此添加到您的 UIViewController
class
它会在您更改设备方向时自动调整您的布局。
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
guard let columnLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
columnLayout.invalidateLayout()
}