gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 21:52:40 27 4
gpt4 key购买 nike

我有以下 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com