0

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

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
}
jerfin
  • 803
  • 1
  • 13
  • 28

2 Answers2

0

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 
    }
Nishant Bhindi
  • 2,242
  • 8
  • 21
0

Try extracting the integer value from the textField and check if it is below 1000.

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