I'm trying to figure out this line which works pretty well for backspace after I restrict user up to 24 characters. But I don't know how it really works.
I tried to figure out the value of range.length
and it's set to 0 if I insert some characters. But I get the value set to 1 when I press the back button while deleting the characters?? Why is this?
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
println("range is \(range)")
println("range location is \(range.location)")
println("range length is \(range.length)")
if (textlength - (range.length) + count(string)) > 24 {
textField.layer.borderColor = UIColor.redColor().CGColor
textField.layer.borderWidth = 1.0
println("\(newString)")
return false
}
return true
}
Try to insert e text 3 characters long. Then select all and hit cut. You should see something like:
range is (0,3)
range location is 0
range length is 3
When you insert you get length 0 since nothing is selected. You just have the cursor position. When you delete your range.length will be the length of the string that could be deleted. When you hit back you just delete the last character, thus the range.length is 1.