I know there are other topics on this but I can't seem to find out how to implement it.
I'm trying to limit a UITextField to only 5 Characters
Preferably Alphanumeric and - and . and _
I've seen this code
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool
{
let maxLength = 4
let currentString: NSString = textField.text
let newString: NSString =
currentString.stringByReplacingCharactersInRange(range, withString: string)
return newString.length <= maxLength
}
and
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let length = count(textField.text.utf16) + count(string.utf16) - range.length
return length <= 10
}
I just don't know how to actually implement it or which "textfield" should I swap out for my custom named UITextField
TextField Limit Character After Block the Text in Swift 4
Simple solution without using delegate:
Here's a Swift 3.2+ alternative that avoids unnecessary string manipulation. In this case, the maximum length is 10:
I use this step, first Set delegate texfield in viewdidload.
and then shouldChangeCharactersIn after you include UITextFieldDelegate.
This answer is for Swift 4, and is pretty straight forward with the ability to let backspace through.
update for this Fattie answer
thanks