Reputation: 312
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
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
Upvotes: 1
Views: 203
Reputation: 831
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.
Upvotes: 0
Reputation: 628
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"
}
Upvotes: 2