Search code examples
iosswiftuilabel

How can I listen for UILabel content changes?


I want to listen the content changes in the UIlabel and prevent it from changing when its length is greater than 7. What should I do? I tried set / get / willset / didset. It seems that it can't meet my needs

I wrote a simple demo ,When I press the button, add a number to display area. I don't want his length to exceed my expectations

enter image description here

In my real project, I'm developing a calculator What I can think of is to judge the length of displayValue, but doing so will make my code wordy


Solution

  • didSet can help you better. add this code in line number 6 in your code.

    var displayValue: String = "" {
        didSet {
            if displayValue.count <= 7 {
                customLabel.text = displayValue
            }
        }
    }
    

    Then in your action function, you need to just do it.

    @IBAction func clickBtn( _ sender: Any) {
        displayValue = displayValue + "0"
    }