ios - 为边界而不是框架工作的属性(property)观察员

标签 ios swift property-observer

我正在做这个项目, Storyboard上有一个场景。

场景是一个 TableViewController。

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

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

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

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

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

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

最佳答案

.frame 是根据 View (和变换)的 .bounds 和 .center 计算的,因此它不会改变。为了对旋转使用react,覆盖这个(从 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)
}

关于ios - 为边界而不是框架工作的属性(property)观察员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36140130/

相关文章:

iphone - 关闭模态视图 Controller

swift - 如果不为零则模式匹配

swift - 在 UICollectionView 中使用自动布局绘制圆圈的正确时机

swift - Swift 中 willSet 和 didSet 的目的是什么?

swift - 为什么在更改现有值的成员时会运行属性观察器?

ios - Facebook iOS SDK 使用 UIWebView 而不是 safari 登录( native 技巧/解决方案)

c# - vNext 类库中的目标 Android/iOS

ios - 如何将字符串拆分为两行标签

ios - 同一个方案,为什么faSTLane xcov的代码覆盖率值和Xcode的值不一样?

swift - 如何设置字符串变量并使其始终小写?