Set the maximum character length of a UITextField

2020-01-24 06:41发布

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

19条回答
forever°为你锁心
2楼-- · 2020-01-24 07:19

The same way Steven Schmatz did it but using Swift 3.0 :

//max Length
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool
{
    let maxLength = 4
    let currentString: NSString = textField.text! as NSString
    let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
    return newString.length <= maxLength
}
查看更多
登录 后发表回答