由于“ autoresizingmask”而导致视图调整大小时,KVO无法用于UIView.bounds关键路径。

问题描述 投票:1回答:2
我有以下视图控制器:

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

childView的大小因调整大小时的自动调整蒙版而自动调整大小。但是,KVO观察并没有得到呼吁。为什么在这种情况下KVO不起作用?

我有以下视图控制器:类ViewController:UIViewController {惰性var superView:UIView = {让视图= UIView(框架:CGRect(x:0,y:0,宽度:300,高度:300))视图... 。

ios swift key-value-observing objective-c-runtime key-value-coding
2个回答
1
投票
我的问题是通过观察superView而不是\.layer.bounds来解决的,因为我了解到该层是视图布局的“真相之源”,因此我怀疑自动调整大小蒙版是否直接修改了层边界而没有经历[ C0]

0
投票
您可以这样操作
© www.soinside.com 2019 - 2024. All rights reserved.