标签:
有时候项目中要求文本框中只能输入数字,如:价格、公里数、费用等等,一般的文本框不限制输入的格式,这时候只能强制限制输入框的输入格式了,代码如下:
#import "ViewController.h"
@interface ViewController ()<UITextFieldDelegate>{
UITextField *numTextField;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
numTextField = [[UITextField alloc] initWithFrame:CGRectMake(60, 80, 100, 40)];
numTextField.layer.borderColor = [[UIColor grayColor]CGColor];
numTextField.layer.borderWidth = 1.0f;
numTextField.delegate = self;
numTextField.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:numTextField];
}
#pragma mark - UITextField限制输入数字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if(textField == numTextField){
return [self validateNumber:string];
}
return YES;
}
#pragma mark - 验证是否是纯数字
- (BOOL)validateNumber:(NSString*)number {
BOOL res = YES;
NSCharacterSet *tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
int i = 0;
while (i < number.length) {
NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
NSRange range = [string rangeOfCharacterFromSet:tmpSet];
if (range.length == 0) {
res = NO;
NSLog(@"请输入数字");
break;
}
i++;
}
return res;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
注:写文章的时候,突然想到了可以设置键盘样式为数字形式(UIKeyboardTypeNumberPad),这样的话应该也是可以限制的,通过模拟器调试,设置键盘样式没有作用,因为用电脑上的键盘可以输入汉字或字母,不知道真机是否可以,感兴趣的可以在真机上测试下。
标签:
原文地址:http://www.cnblogs.com/alina06/p/5789619.html