ios - 由于 `UIView.bounds` 发生 View 调整大小时,KVO 不适用于 `autoresizingmask` key 路径

标签 ios swift key-value-observing objective-c-runtime key-value-coding

我有以下 View Controller :

class ViewController: UIViewController {

  lazy var superView: UIView = {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
    view.backgroundColor = UIColor.white
    return view
  }()

  lazy var childView: UIView = {
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view.backgroundColor = UIColor.black
    return view
  }()

  var boundObservation: NSKeyValueObservation?

  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.backgroundColor = UIColor.orange

    self.view.addSubview(self.superView)
    self.superView.center = CGPoint(
      x: self.view.frame.width / 2.0,
      y: self.view.frame.height / 2.0
    )

    self.superView.addSubview(self.childView)
    self.childView.center = CGPoint(
      x: self.superView.frame.width / 2.0,
      y: self.superView.frame.height / 2.0
    )
    self.childView.autoresizingMask = .flexibleWidth

    let button = UIButton(type: .system)
    button.setTitle("Tap me!", for: .normal)
    button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    self.view.addSubview(button)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
    button.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -24).isActive = true

    self.boundObservation = self.childView.observe(
      \UIView.bounds,
      options: .new,
      changeHandler: { view, change in
        print(change.newValue ?? "nil")
    })
  }

  @objc func buttonTapped(_ sender: UIButton) {
    let view = self.superView
    let previousSize = view.bounds.size
    view.bounds.size = CGSize(width: previousSize.width + 50, height: previousSize.height + 20)
  }
}

我的 childViewsuperView 时,由于自动调整掩码,get 会自动调整大小被调整大小。但是 KVO 观察没有被调用。为什么 KVO 在这种情况下不起作用?

最佳答案

通过观察 \.layer.bounds 解决了我的问题而不是 \UIView.bounds因为我了解到图层是 View 布局的“真实来源”,所以我怀疑自动调整大小的蒙版直接修改了图层边界而不通过 UIView.bounds

关于ios - 由于 `UIView.bounds` 发生 View 调整大小时,KVO 不适用于 `autoresizingmask` key 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61474938/

相关文章:

ios - 上传 iOS 应用程序时应用程序加载器卡在 "Authenticating with the iTunes store"

ios - 如何重定向到 Google map (如果已安装),否则重定向到 Appstore 以使用 Swift 安装 Google map

ios - 注销 KVO 时崩溃

Cocoa:在控制绑定(bind)中避免 'Updates Continuously'

ios - X-Apple-Store-Front 在苹果 http header 中意味着什么?

xcode - 检查您是否已经在 Game Center/GameKit 中解锁成就

swift - 如何在 Swift 中创建可导入模块?

iOS Strech 动画 - 我应该从哪里开始寻找?

iOS:动画在 observeValueForKeyPath 中不起作用

ios - iOS 中的 ContentView V/S SuperView?