简体   繁体   中英

Max Character Limit for TextField

I am looking to cap the amount of characters a user can type into a textfield at 14. Here is the code that I have found documentation on.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    let currentCharacterCount = userNameTextField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount){
        return false
    }
    let newLength = currentCharacterCount + string.characters.count - range.length
    return newLength <= 14
}

but I do not feel that I am implementing this correctly. I have set

userNameTextField.delegate = self 

in the viewDidLoad, and I am conforming to the UITextFieldDelegate protocol.

You state you are using Swift 3. The signature of many methods changed in Swift 3. You need to use:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
}

Not the old signature posted in your question.

If it's still not being called, then you never set the text field's delegate property.

Try this instead:

func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
    let currentString: NSString = (textField.text ?? "") as NSString
    let newString = currentString.replacingCharacters(in: range, with: string)
    return  newString.characters.count <= 14
}

Try this for swift 3:

let limit=4;

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = txtSMSCode.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= limit
}

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