To prevent the user from inputting more than one decimal into the text field and to prevent the user from inputting alphabetical characters into the text field I have tried the code below. The problem is I don't know how to check them both within the function and have two If statements which means the second one won't run as it never gets executed. If I take the code that checks number of decimals out and leave the character checker code it works perfectly. How can I get them both working though?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = textField.text?.rangeOfString(".")
let replacementTextHasDecimalSeparator = string.rangeOfString(".")
let charactersNotAllowed = NSCharacterSet.letterCharacterSet()
let replacementTextHasLetter = string.rangeOfCharacterFromSet(charactersNotAllowed)
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
if replacementTextHasLetter != nil {
return false
} else {
return true
}
}
The reason your function does not work is that it makes its decision early for both the positive and the negative case.
Defer returning true
to the very end of the function:
if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil {
// Do not allow multiple decimal separators
return false
}
if replacementTextHasLetter != nil {
// Do not allow letters
return false
}
return true
This reflects the all-or-nothing logic of the decision: all checks must succeed in order to all checks, while it takes only one failed check to reject the change.