1.添加监听 lab1.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil) 2. 监听 override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let old = change?[NSKeyValueChangeKey.oldKey] { print("old = \(old)") // } if let new = change?[NSKeyValueChangeKey.newKey] { print("new = \(new)") // Albert } } 3.移除KVO deinit { lab1.removeObserver(self, forKeyPath: "text") }
2.添加多个KVO
lab1.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil) lab1.addObserver(self, forKeyPath: "frame", options: .new, context: nil) override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "text"{ print("text改变") }else{ print("frame 改变") } if let old = change?[NSKeyValueChangeKey.oldKey] { print("old = \(old)") // } if let new = change?[NSKeyValueChangeKey.newKey] { print("new = \(new)") // Albert } } deinit { lab1.removeObserver(self, forKeyPath: "text") lab1.removeObserver(self, forKeyPath: "frame") }
3. 两个label 都监听了 text, frame
lab1.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil) lab1.addObserver(self, forKeyPath: "frame", options: .new, context: nil) lab2.addObserver(self, forKeyPath: "text", options: [.new, .old], context: nil) lab2.addObserver(self, forKeyPath: "frame", options: .new, context: nil) override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if lab1.isEqual(object){ print("lab1 改变") if keyPath == "text"{ print("lab1 text改变") if let old = change?[NSKeyValueChangeKey.oldKey] { print("old = \(old)") // } if let new = change?[NSKeyValueChangeKey.newKey] { print("new = \(new)") // Albert } }else{ print("lab1 frame 改变") if let old = change?[NSKeyValueChangeKey.oldKey] { print("old = \(old)") // } if let new = change?[NSKeyValueChangeKey.newKey] { print("new = \(new)") // Albert } } }else{ print("lab2 改变") if keyPath == "text"{ print("lab2 text改变") }else{ print("lab2 frame 改变") } } } deinit { lab1.removeObserver(self, forKeyPath: "text") lab1.removeObserver(self, forKeyPath: "frame") lab2.removeObserver(self, forKeyPath: "text") lab2.removeObserver(self, forKeyPath: "frame") }