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.

为了实现这一点,我创建了以下函数:

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)
}

这在第一次加载时可以正常工作,但是当我旋转设备时,计算不总是再次发生,视图也不总是按照预期重新绘制.以下是我在旋转设备时的代码:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    collectionView.collectionViewLayout.invalidateLayout()
    self.view.setNeedsDisplay()
}

我想我忘了重画一些东西,但我不确定是什么.非常感谢您的任何意见!

推荐答案

你可以用viewWillLayoutSubviews.This question应该很有帮助,但每当视图控制器视图即将布局其子视图时,都会基本上调用它.

因此,您的代码将如下所示:

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()
}

Swift相关问答推荐

运行异步任务串行运行

如何使用变量 Select 哪个向量(?)在我的 struct 中密谋吗?

如何使用AsyncTimerSequence获取初始时钟,然后在指定的时间间隔内开始迭代?

文件命名&NumberForMatter+扩展名&:含义?

SwiftUI 组合问题:通过 AppEventsManager 在 ViewModel 之间共享数据

将变量设置为 @Published 会 destruct 代码而不会出现任何错误

Swift Property Wrappers-Initialization 失败并显示无法将‘Double’类型的值转换为预期的参数类型

如何将视图添加到多行文本视图的末尾?

swift 是否遇到 Java 的 2gb 最大序列化大小问题?

快速递归:函数与闭包

如何在 SwiftUI 中将图像传递到 2 个视图

Swift初始化具有可变ID的重复值数组

调用从 SwiftUI 视图传递到 PageViewController.Coordinator 的函数

用于 Swift 编码的 iOS 应用程序的 Ffmpeg

在 Swift 中,如何查看 Process() 传递给 shell 的字符串?

无法使用锚激活约束

iOS Swift - 如何更改表格视图的背景 colored颜色 ?

更新我的 pod 导致 GoogleDataTransport Umbrella 标头出现错误

如何在 Swift 中使用 Crashlytics 登录?

如何在 Swift 中判断变量的类型