简体   繁体   中英

how to set the maximum 4 digit number in uitextfield using swift3.0

I use this code but it should return anyone. But I need to use this two scenarios. So how can I change this? Anyone help me. I restrict a (.0 symbol and at the same time only allowed 4 digit amount. How can i do this.???

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

    guard let text = amountField.text else { return true }
    let newLength = text.characters.count + string.characters.count - range.length
    return newLength <= 4 // Bool

   let ACCEPTABLE_CHARACTERS = "1234567890"
    let cs = CharacterSet(charactersIn: ACCEPTABLE_CHARACTERS).inverted
    let filtered: String = string.components(separatedBy: cs).joined(separator: "")
    return string == filtered



}

Possible solution for your issue.

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

    var newLength = string.utf16.count - range.length

    if let text = textfield.text {
        newLength = text.utf16.count + string.utf16.count - range.length
    }

    let characterSet = NSMutableCharacterSet()
    characterSet.addCharacters(in: "1234567890")

    if string.rangeOfCharacter(from: characterSet.inverted) != nil || newLength > 4 {
        return false
    }
    return true
}

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