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

前端 未结 5 1189
后悔当初
后悔当初 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条回答
  •  情书的邮戳
    2021-01-03 14:28

    In its most basic form you can do this:

    - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range
    replacementString:(NSString*)string
    {
        NSString* newText;
    
        newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
        return [newText intValue] < 1000;
    }
    

    However, you also need to check if newText is an integer, because intValue returns 0 when the text starts with other characters.

提交回复
热议问题