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
Your view controller should conform to
UITextFieldDelegate
, like below:Set the delegate of your textfield:
myTextField.delegate = self
textField(_:shouldChangeCharactersInRange:replacementString:)
All together:
For Swift 4
Allowing only a specified set of characters to be entered into a given text field
How to program an iOS text field that takes only numeric input with a maximum length
My Swift 4 version of
shouldChangeCharactersIn
I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse. And there is no leak problem here.
Simply just check with the number of characters in the string
Note: Here I checked for only char allowed in textField
Working In Swift4
// STEP 1 set UITextFieldDelegate
// STEP 2 set delegate
userMobileNoTextFiled.delegate = self //set delegate }
// STEP 3 call func
Swift 5
Credit: http://www.swiftdevcenter.com/max-character-limit-of-uitextfield-and-allowed-characters-swift/
Just write one to set max char length
For more detial click here