Reputation: 559
I'm getting to grips with the text field functions that allow you to check for when "didEndEditing" or "shouldStartEditing" take place.
I've got this working fine when I have 2 text fields and one button. If I want to enable the button after some validation has taken place I use "didEndEditing" to do some validation and enable the button if everything is okay when the user clicks into the other field.
Problem If you have only one text field and one button on a page, where I require only integers be allowed for the input in the text field before enabling the button, how do I achieve this?
i.e. button is disabled. As I input text into the text field, if only integers then enable button. If anything else don't, in real time as you are typing.
As there is only one text field, I don't think I can use "didEndEditing" because you never 'leave' the text field (there's nothing else to click on)
What have I tried I've tried this :
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
print("While entering the characters this method gets called")
if textField === timeInputField {
//set which characters are valid
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
//if text isn't empty then hide the error label ("must input a time")
if timeInputField.text?.isEmpty == false {
timeInputErrorLabel.isHidden = true
}
//if the string returns values in the range set button to enabled
return string.rangeOfCharacter(from: invalidCharacters, options: [], range: string.startIndex ..< string.endIndex) == nil
} else {
doWorkoutButtonOutlet.isEnabled = true
}
return true
}
I think i'm essentially trying to achieve this Need to enable button when text is entered in field. in Swift 4!
Upvotes: 0
Views: 1702
Reputation: 4391
This will prevent anything other than integers entering the textField
. Don’t forget to do a check for which textField
if using more than one.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
if numbers.contains(string ?? "") {
// Validate text for button enabling
if let stringValue = textField.text {
if let number = Int(stringValue) {
yourButton.isEnabled = true
// Text validated as an integer. Can use value of number if desired
} else {
yourButton.isEnabled = false
}
} else {
yourButton.isEnabled = false
}
// Return true to update field with new character
return true
} else {
// Return false as entered character is not a digit 0-9
return false
}
}
You can also validate text in this delegate method:
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if let stringValue = textField.text {
if let number = Int(stringValue) {
yourButton.isEnabled = true
// Do something with number value
return true
}
}
return false
}
Upvotes: 1