简体   繁体   中英

Limit TextField Input to Capitals letters, Numbers and Character limit of 6?

I've searched online and found a lot of examples on limiting TextFields, but I can't find any on limiting multiple factors. The Code I'm working messes up the input and I cant figure out why.

Heres my code: (Note: I have already set the delegate)

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = LPinput.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
    return newLength <= limitLength
}

Here's what I type into the TextField:

food

And here's what is shown in the TextField:

FfOoOoD

Please help!

As @rmaddy says, The problem is that you are modifiying the UITextField.text property and returning true after that, this cause the duplicated behavior founded in your question, so I change that and first check the textLength and after that modify the text and return always false to avoid adding duplicate characters try with this code

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = LPinput.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    if(newLength <= limitLength)
    {
    LPinput.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
    }
    return false
}

Hope this helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM