【问题标题】:how .addObservers and observevalue method works in iOS Swift 5.addObservers 和 observevalue 方法如何在 iOS Swift 5 中工作
【发布时间】:2021-12-03 05:52:12
【问题描述】:

我正在为我的 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()
                }
            }
      

【问题讨论】:

    标签: ios swift key-value-observing


    【解决方案1】:

    我认为最好阅读文档。没有人会比官方文档更好地解释你。键值观察是一个众所周知的,不是新的和有据可查的概念。您可以从this specific method docs 开始(易于搜索)。并从那里移动到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 类实现了这个机制。所有UIViewController 子类也是NSObject 的后代,并免费提供相同的功能。

    【讨论】:

      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多