0

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?

2 Answers2

0

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.

Johnykutty
  • 12,091
  • 13
  • 59
  • 100
0

UIButton is not KVO compliant for the key "title".

None of the Apple provided framework objects is supposed to be used with KVO, unless documented otherwise (see here, here or here). It might work in some cases, but it's fragile and bad code.

You have to use other means to react on label changes.

Community
  • 1
  • 1
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • that was for test purpose and it worked fine after if changed the keypath to "text" as i was observing the button title... –  Oct 30 '15 at 08:17
  • @swiftBUTCHER No harm done if KVO is used like this for debugging. Just make sure the code is removed before going to production. – Nikolai Ruhe Oct 30 '15 at 08:21
  • ok..that was just for self learning never ever used KVO :)..but can you please tell me when to use these NSKeyValueObservingOptions.New or Old –  Oct 30 '15 at 08:24