我需要检测 subview 数量何时发生变化并执行作业。如何添加观察者并在发生变化时获取回调?
到目前为止,我已经在 AppDelegate
中尝试过:
private func setupObserver() {
window?.addObserver(self, forKeyPath: "subviews.count", options: NSKeyValueObservingOptions.new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print(keyPath)
}
但它崩溃了:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '[<__NSArrayM 0x6000002520f0> addObserver:forKeyPath:options:context:] is not supported. Key path: count'
最佳答案
KVO 之外的另一种解决方案
您可以按如下方式对 UIWindow
进行子类化
class MyWindow: UIWindow {
override func didAddSubview(_ subview: UIView) {
print("Subview added")
}
}
然后在AppDelegate
中,您可以覆盖window
属性,如下所示
var _window: MyWindow?
var window: UIWindow? {
get {
_window = _window ?? MyWindow(frame: UIScreen.main.bounds)
return _window
}
set { }
}
现在,每当添加新对象时,都会调用重写的方法 didAddSubview
。您可以根据需要重写更多方法。
didAddSubview(:) , willRemoveSubview( :) , willMove(toSuperview:) , didMoveToSuperview()
摘录window
属性(property)
The default value of this synthesized property is nil, which causes the app to create a generic UIWindow object and assign it to the property. If you want to provide a custom window for your app, you must implement the getter method of this property and use it to create and return your custom window.
关于ios - 如何在 UIView 中添加 subviews.count 的观察者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46605047/