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))视图... 。
superView
而不是\.layer.bounds
来解决的,因为我了解到该层是视图布局的“真相之源”,因此我怀疑自动调整大小蒙版是否直接修改了层边界而没有经历[ C0]