Obj-C,如何确保用户在 UITextField 中输入 1 或以上?
过去,我曾设法限制 shouldChangeCharactersInRange
事件中文本字段的长度,并应用货币格式。
然而这一次,我需要确保用户输入1或以上。
所以 0001 是不可接受的,因为零需要是 1 到 1000000。
我该怎么做?
这就是我到目前为止所拥有的
- (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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
UI 的一个好规则是:“在你做的事情上保持自由
接受,并且在发送的内容上保守”*。
不要因为不符合应用程序想要的格式的输入而惩罚用户,而是接受任何可以转换为正确格式的内容。如果您想要一个介于 1 和 1 之间的整数包含百万,0001 是一个奇怪但完全有效的输入,我建议这个解决方案:
*:最初由 John Postel 制定为 “稳健性原则” 可能有更具体的 UI 说明,但我现在不记得了。;
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:
*: 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.