如题,记录下swift中监听自定义属性失效的问题
极简单的例子
import UIKit
class HZJViewController: UIViewController {
var name:String = "one"
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.addObserver(self, forKeyPath: "name", options: [.old,.new], context: nil)
}
deinit {
self.removeObserver(self, forKeyPath: "name")
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "name" {
print(change)
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.name = "two"
}
}
处理方法:添加@objc和dynamic
@objc dynamic var name:String = "one"
至于原因,各位还是百度吧,不想copy。。[旺柴]
来源:oschina
链接:https://my.oschina.net/wshzj/blog/4309414