iosswiftkey-value-observing

how .addObservers and observevalue method works in iOS Swift 5


I am using tableView.addObserver and observeValue method for my Swift project to give tableView Height according to its content. its working completely fine but I don't know how. can someone please explain me with this here's my code.

 

    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()
                }
            }
      

Solution

  • I think it's better to read documentation. No one would explain you better than official documentation. Key-Value observing is a well-known, not new and well documented concept. You can start with 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.
    

    So it mentions that NSObject class has this mechanism implemented. All UIViewController subclasses are also descendants of NSObject and have the same functionality included for free.