简体   繁体   English

如何在输入过程中设置最大数值

[英]How to set the maximum number of value during typing

I have a UITextField, I'd like to restrict the maximum allowed input value in the field to be 1000 .eg (1-1000),If the value in the textfield exceeds above 1000 the textfield should not get the value as input.I have tried the following 我有一个UITextField,我想将字段中允许的最大输入值限制为1000,例如(1-1000),如果文本字段中的值超过1000,则文本字段不应获取该值作为输入。尝试了以下

func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
    var newString: String = textField.text.replacingCharacters(in: range, with: string)
    var characterSet = CharacterSet(charactersIn: "0123456789,.").inverted
    if (newString as NSString).rangeOfCharacter(from: characterSet).location != NSNotFound {
        return false
    }
    return Double(newString) ?? 0.0 < 1000
}

Try this. 尝试这个。 Hope this will help 希望这会有所帮助

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

Try extracting the integer value from the textField and check if it is below 1000. 尝试从textField中提取整数值,然后检查它是否小于1000。

- (BOOL)textFieldShouldReturn:(UITextField *)textField
  {
      NSInteger inte = [textField.text intValue];
      if (inte < 1000 && inte > 0)
         return NO;
      else 
         return YES;
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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