swift 中的KVO用法
import UIKit
class ViewController: UIViewController {
@IBOutlet var btn: UIButton!
var myContext:NSObject!
override func viewDidLoad() {
super.viewDidLoad()
myContext = NSObject()
btn.addObserver(self, forKeyPath: "backgroundColor", options: .new, context: &myContext)
}
@IBAction func btnClicked(_ sender: Any) {
btn.backgroundColor = UIColor.red
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext {
if let newValue = change?[NSKeyValueChangeKey.newKey] {
print("Date changed: \(newValue)")
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
deinit {
btn.removeObserver(self, forKeyPath: "titleColor", context: &myContext)
}
}Last updated