genaks genaks - 2 months ago 25
Swift Question

Detect UILabel text change in swift

Is there a way to get notified when there is a change in a

UILabel
's text or would I be better off using a
UITextField
with
userInteractionEnabled
set to
false
and using its
UIControlEditingChanged
event to fulfil my purpose?

For ex. I need to run certain lines of code every time I change the
UILabel
's text and accordingly. So instead of writing those 100 lines of almost similar code for every case I change the
UILabel
's text, I wish to write it together in one place and call it every time the
UILabel
is changed. I don't even know if that makes any sense. Forgive me but I cannot expose much of the code.

Answer

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"
Comments