Reputation: 1409
I am building a digit only textfield.
I would like that when the text in textfield is "" replace it with "0".
I only manage to get the current text in read only.
Thanks in advance
Upvotes: 0
Views: 430
Reputation: 5554
If you want the text field to update when you have finished editing you can set up the action like this
and then
@IBAction func editingDidEnd(_ txtTest: UITextField) {
if txtTest.text == ""
{
txtTest.text = "0"
}
Upvotes: 1
Reputation: 657
Add the editingChanged
delegate method to textField
as follows:
In the viewDidLoad()
method add the following code:
textField.addTarget(self, action: #selector(textFieldChanged(_:)), for: .editingChanged);
And then, implement the method as follows:
@objc func textFieldChanged(_ textField: UITextField) {
if let text = textField.text, text.isEmpty {
textField.text = "0"
}
}
The above method will be called every time the textField content changes.
You can also set the initial text of the textField
to "0". Simply use textField.text = "0"
in the viewDidLoad()
method.
Upvotes: 1
Reputation: 82
textField.addTarget(self, action: #selector(handleTextField(_:)), for: .editingChanged)
@objc private func handleTextField(_ textField: UITextField) {
if textField.text == "" {
textFiled.text = "0"
}
}
Upvotes: 0