ios - 如何在 UIView 中添加 subviews.count 的观察者?

标签 ios swift

我需要检测 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/

相关文章:

ios - 如何从 Storyboard 静态单元格中的 UIButton 触发 IBAction?

ios - swift 3 : UILabel not showing in custom UITableViewCell

macos - Swift 中的 Cocoa 授权

ios - Nib 高度何时设置?

ios - Xamarin iOS : Refresh page from viewModel

ios - TestFlight不可用

ios - 如何为多个设备实现核心蓝牙功能?

swift - Xcode Swift 快速帮助闭包

ios - 太多的文字将我的按钮推到屏幕下方

ios - 向下/向上滚动时,uitableview 中的 uitextfield 文本已被重置 iOS