开发者

Obj-C, how do I ensure users enter 1 or above in a UITextField?

In the past, I've managed to limit the length of a textfield in the shouldChangeCharactersInRange event and also apply currency formatting.

However this time, I need to ensure that the开发者_开发知识库 user enters 1 or above.

So 0001 would be unacceptable as would zero it needs to be 1 through 1000000.

How would I do this ?

This is what I have so far

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
   (NSRange)range replacementString:(NSString *)string {

    BOOL res = TRUE;

    NSString *newString = [textField.text stringByReplacingCharactersInRange:
      range withString:string];
    newString = [NSString stringWithFormat:@"%d", [newString intValue]];
    res = !([newString length] > 8);

    return res;
}


A good rule for UI is: "Be liberal in what you accept, and conservative in what you send"*.

Rather than punish the user for input which doesn't fit the format your app would like, accept anything that can be transformed into the proper format. If you want an integer between one and one million inclusive, 0001 is a weird but perfectly valid input. I suggest this solution:

// Only check the value when the user is _done_ editing.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {

    NSInteger intVal = [textField.text integerValue];
    // Check whether the input, whatever it is, 
    // can be changed into an acceptable value
    if( (intVal <= 1000000) && (intVal >= 1) ){
        // If so, display the format we want so the 
        // user learns for next time
        textField.text = [[NSNumber numberWithInteger:intVal] stringValue];
        return YES;
    }

    // Else show a small error message describing 
    // the problem and how to remedy it
    return NO;
}

*: Originally formulated by John Postel as the "Robustness Principle"; there may be a more UI-specific statement of it, but I can't recall at the moment.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜