Detect UILabel text change in swift

Swift 3

First, add an observer to UILabel for key path text.

label.addObserver(self, forKeyPath: "text", options: [.old, .new], context: nil)

Then

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
  if keyPath == "text" {
    print("old:", change?[.oldKey])
    print("new:", change?[.newKey])
  }
}

Swift 2

label.addObserver(self, forKeyPath: "text", options: [.Old, .New], context: nil)

Then

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if keyPath == "text" {
        print("old:", change["old"])
        print("new:", change["new"])
    }
}

Console Output

For example console would be:

old: Optional(<null>)
new: Optional(ABC)

Create a class that inherits from UILabel. Such as:

class YourLabel: UILabel {

    override var text: String? {
        didSet {
            if let text = text {
                println("Text changed.")
            } else {
                println("Text not changed.")
            }
        }
    }
}

Create a outlet of this class for your object.

@IBOutlet weak var label: YourLabel!
label.text = "abc"

You can do this simply with a subclass of UILabel:

class Label : UILabel {
    override var text: String? {
        didSet {
            print("Text changed from \(oldValue) to \(text)")
        }
    }
}

oldValue is a special value provided by Swift. See Property Observers

Tags:

Ios

Swift