0

我正在做这个项目,我在故事板上有一个场景。

场景是一个 TableViewController。

  • 表格视图有一个自定义原型单元格(链接到 CustomCell.swift)。

    • 在原型单元格内有一个标签和一个自定义 UIView(链接到 CustomView.swift)。这些元素具有相对于原型单元格的 contentView 的布局约束。

现在,我希望在我的自定义视图上绘制的内容在视图大小发生变化时发生变化,以便在设备旋转时将其调整为新的单元格宽度。由于限制,在设备旋转后,当 CustomCell 改变大小时,CustomView 的框架会发生变化。为了检测到这一点,我在 CustomView.swift 中添加了两个属性观察器:

override var frame: CGRect {
    didSet {
        print("Frame was set!")
        updateDrawing()
    }
}

override var bounds: CGRect {
    didSet {
        print("Bounds were set!")
        updateDrawing()
    }
}

运行项目时,当我旋转设备时,第二个观察者工作正常。第一个观察者没有。我的问题是为什么第一个观察者没有检测到框架已经改变?

4

1 回答 1

2

.frame 是从 .bounds 和视图(以及变换)的 .center 计算出来的,所以它不会改变。为了响应旋转覆盖这个(从iOS8开始):

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    coordinator.animateAlongsideTransition({ (coordinator) -> Void in
        // do your stuff here
        // here the frame has the new size
    }, completion: nil)
}
于 2016-03-21T20:26:15.840 回答