shouldChangeCharactersInRange
does the following (Quoted from the docs)
Asks the delegate if the specified text should be changed.
Your added code to this method checks if it exceeds your limit (In your example, it is 10) and returns false which means that the textField should not change values. If it did not exceed the limit, it will return true, and the textField will change values.
To do this for multiple textFields, you will need to have outlets to your multiple textFields, and then a simple if statement inside this method will do the job.
@IBOutlet weak var textfield1: UITextField!
@IBOutlet weak var textfield2: UITextField!
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let newLength = textField.text.characters.count + string.characters.count - range.length
if textField == textField1 {
return newLength <= 10 // Bool
} else if textField == textField2 {
return newLength <= 15 // Bool
}
return true
}
To be able to use the above method in your code, your UIViewController
which contains these textFields will need to implement the UITextFieldDelegate
protocol, and then by setting the UITextField
's delegate property to be that UIViewController
.
Also regarding the count
method. It has been updated many times. To count the number of characters for a string:
Before Swift1.2 -> countElements(string)
Swift1.2 -> count(string)
Swift2 -> string.characters.count