Home > Net >  How can I listen for UILabel content changes?
How can I listen for UILabel content changes?

Time:10-06

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

CodePudding user response:

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

CodePudding user response:

For counting the characters inside a label you use the count method in the text property like this

@IBOutlet weak var testLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    testLabel.text = "duck"
    print(testLabel.text.count) //return 4
}

For user action you can't use the UILabel since it's not user interactive, you have to use the UITextField and connect to him an UIAction or explain us better what you want to do.

  • Related