.addObservers 和 observevalue 方法如何在 iOS Swift 中工作 5

how .addObservers and observevalue method works in iOS Swift 5

我正在为我的 Swift 项目使用 tableView.addObserver 和 observeValue 方法来根据其内容赋予 tableView 高度。它工作得很好,但我不知道如何。有人可以用这个解释我吗 这是我的代码。

 

    override func viewDidLoad() {
                super.viewDidLoad()
                self.tableView.addObserver(self, forKeyPath: "contentSize", options:         NSKeyValueObservingOptions.new, context: nil)
          }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
                tableView.layer.removeAllAnimations()
                heightTable.constant = tableView.contentSize.height
                UIView.animate(withDuration: 0.5) {
                    self.updateViewConstraints()
                }
            }
      

我认为阅读文档更好。没有人能比官方文档更好地向您解释。 Key-Value observing 是一个众所周知的,不是新的并且有据可查的概念。您可以从 this specific method docs (easy to search). And move from there to the general topic:

开始
NSKeyValueObserving

An informal protocol that objects adopt to be notified of changes to the
specified properties of other objects.

Overview

You can observe any object properties including simple attributes, to-one
relationships, and to-many relationships. Observers of to-many relationships 
are informed of the type of change made — as well as which objects are 
involved in the change.

NSObject provides an implementation of the NSKeyValueObserving protocol that 
provides an automatic observing capability for all objects. You can further 
refine notifications by disabling automatic observer notifications and 
implementing manual notifications using the methods in this protocol.

所以提到NSObject class实现了这个机制。所有 UIViewController 子 class 也是 NSObject 的后代,并且免费包含相同的功能。