I would like to be able to restrict the characters that can be entered into a textfield, for instance I want to restrict to only 1-5 numbers (1,2,3, and 5) and if the user enters a number greater than 5, I want the textField to do nothing.
I have seen how to restrict the length but I couldn't find anything for restricting certain character as I'm describing above.
I tried using the editingQtyFieldChanged
but it doesn't quite do what I want.
myField.addTarget(self, action: #selector(UserInputViewController.fieldChanged), forControlEvents: UIControlEvents.EditingChanged)
func fieldChanged(){
let number = Int(myField.text!)
if number < 2{
print("Number not allowed")
}
}
Restrict to only numbers 1-5 in a uitextfield in Swift?
EDIT: Here is my solution, thanks to this thread.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let numbers = ["6","7","8", "9"]
for number in numbers{
if string == number{
return false
}
}
}