有時候項目中要求文本框中只能輸入數字,如:價格、公裡數、費用等等,一般的文本框不限制輸入的格式,這時候只能強制限制輸入框的輸入格式了,代碼如下:
#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),這樣的話應該也是可以限制的,通過模擬器調試,設置鍵盤樣式沒有作用,因為用電腦上的鍵盤可以輸入漢字或字母,不知道真機是否可以,感興趣的可以在真機上測試下。