UITextField : restrict the maximum allowed value (number) during inputting

前端 未结 5 1161
后悔当初
后悔当初 2021-01-03 14:17

I have a UITextField, I\'d like to restrict the maximum allowed input value in the field to be 1000. That\'s when user is inputting number inside, once the inpu

5条回答
  •  -上瘾入骨i
    2021-01-03 14:23

    I created a class with the help method that can be call from any place in your project.

    Swift code:

    class TextFieldUtil: NSObject {
    
        //Here I am using integer as max value, but can change as you need
        class func validateMaxValue(textField: UITextField, maxValue: Int, range: NSRange, replacementString string: String) -> Bool {
    
            let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)
    
            //if delete all characteres from textfield
            if(newString.isEmpty) {
                return true
            }
    
            //check if the string is a valid number
            let numberValue = Int(newString)
    
            if(numberValue == nil) {
                return false
            }
    
            return numberValue <= maxValue
        }
    }
    

    Then you can use in your uiviewcontroller, in textfield delegate method with any textfield validations

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        if(textField == self.ageTextField) {
            return TextFieldUtil.validateMaxValue(textField, maxValue: 100, range: range, replacementString: string)
        }
        else if(textField == self.anyOtherTextField) {
            return TextFieldUtils.validateMaxValue(textField, maxValue: 1200, range: range, replacementString: string)
        }
        return true
    }
    

提交回复
热议问题