简体   繁体   中英

Swift Text Field (IOS, Xcode 7.3, Swift 2): User keys in 4 digits. how to limit input to numeric and limit the number of digits to exactly 4

App requires User to input 4 digits into a Text Field. How do you limit it to just 4? and how to limit to Numeric?

here is a code snippet --> don't forget set a delegate on UITextField

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let nonNumberSet = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    if (string.stringByTrimmingCharactersInSet(nonNumberSet).characters.count > 0 && textField.text?.characters.count < 4) || (string.characters.count == 0 && range.length > 0) {
        return true
    }
    return false
}

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