I am trying to observe the change in UIButton title using KVO pattern.Added observer in viewDidLoad
.
@IBOutlet weak var KVOBTn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
KVOBTn.titleLabel!.addObserver(self, forKeyPath: "btntest", options: NSKeyValueObservingOptions.New | NSKeyValueObservingOptions.Old , context: nil)
}
This is the method that listens if there is any change in the title
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "btntest"{
KVOBTn.backgroundColor = UIColor.greenColor()
}
}
I have changed the button title through another button action
@IBAction func changeTitle(sender: AnyObject) {
KVOBTn.setTitle("testAgain", forState: UIControlState.Normal)
}
The thing is the observeValueForKeyPath
method is never being called.What am i doing wrong?
Your add observer code is not proper, it should be like
KVOBTn.titleLabel!.addObserver(self, forKeyPath: "text", options: [.New, .Old] , context: nil)
Note that the key path is "text"
not "btntest"
. UILabel dent have a key path "btntest"
Also don't forget to chage the check in observeValueForKeyPath
method
UPDATE
This forKeyPath: "text"
really mater. This means you are observing the change for property text
of the buttons title label. If you want to observe change in the text color of the label, the key path should be textColor
UPDATE 2
I am not recommending to use KVO with UI kit elements. KVO usually use for observing changes in model objects. Please don't misinterrupt.