我正在為我的 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()
}
}
我認為最好閱讀文檔。沒有人會比官方文檔更好地解釋你。鍵值觀察是一個眾所周知的,而不是新的和有據可查的概念。您可以從這個特定的方法文檔開始(易於搜索)。然後從那裡轉到一般主題:
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
類已經實現了這種機制。所有UIViewController
子類也是其後代,NSObject
並免費提供相同的功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句