Objective-C:仅限数字文本字段? [英] Objective-C: Numbers only text field?
本文介绍了Objective-C:仅限数字文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Iphone UITextField只有整数
我想放置一个文本字段只接受数字(0-9,甚至不需要小数),但即使使用数字键盘输入选项,我仍然会得到一个带有各种符号的键盘。是否有更好的控制,是否有更好的控制我正在做什么,或者我只需要手动验证输入?
I want to place a text field that only accepts numbers (0-9, doesn't even need decimals), but even using the "Number Pad" entry option I still get a keyboard with various symbols on it. Is there a better control for this, is there a better control for what I'm doing, or do I just have to validate input manually?
推荐答案
以下代码将允许您仅输入数字以及限制可以使用的字符数。
The following code will allow you to only input numbers as well as limit the amount of characters that can be used.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
/* limit to only numeric characters */
NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
for (int i = 0; i < [string length]; i++) {
unichar c = [string characterAtIndex:i];
if ([myCharSet characterIsMember:c]) {
return YES;
}
}
/* limit the users input to only 9 characters */
NSUInteger newLength = [customTextField.text length] + [string length] - range.length;
return (newLength > 9) ? NO : YES;
}
这篇关于Objective-C:仅限数字文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文