Reputation:
I'm making an application and part of it has a sort of calculator functionality.
Users have 4 UITextField
s to which they input numbers, all of which should be optional - but if they are left empty, it should act as if they have entered "0" into the field.
How do I go about setting this default value of 0?
It's currently set so that the initial value in the UITextField
is 0, but this can be deleted by the user (rendering an error), and doesn't allow for placeholder text.
Upvotes: 3
Views: 3339
Reputation: 11242
You have set the default value of the textField to "0"
textField.text = "0"
Now you need to check if the user has changed the textField
and if the change has resulted in an empty text field.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let textFieldString = textField.text, let range = Range(range, in: textFieldString) else {
return false
}
let newString = textFieldString.replacingCharacters(in: range, with: string)
if newString.isEmpty {
textField.text = "0"
return false
} else if textField.text == "0" {
textField.text = string
return false
}
return true
}
Upvotes: 1