This code allows the users to type in certain characters only:
let allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.";
func textField(
textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String)
-> Bool
{
let set = NSCharacterSet(charactersInString: allowedChars);
let filtered = string
.componentsSeparatedByCharactersInSet(set)
.joinWithSeparator("");
return filtered != string;
}
Assign a value to the tag on your textfield that is unique to it (for example, 1).
txtField1.tag = 1
Then, update your method like this:
func textField(
textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String)
-> Bool
{
if textField.tag == 1 {
let set = NSCharacterSet(charactersInString: allowedChars)
let filtered = string
.componentsSeparatedByCharactersInSet(set)
.joinWithSeparator("")
return filtered != string
}
return true
}
You can also omit the ; in Swift.