今天项目中有个文本框需要只可以输入数字的需求,首先在.xib中将UITextField的Keyboard设置为Number Pad,但是使用时键盘会切回别的键盘无法对内容进行校验。通过神奇的百度我知道了通过以下方法可以解决这样的问题:
首先让.xib的viewController实现UITextFieldDelegate然后和想要校验的控件关联。
然后将下列代码粘贴到类中即可。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { return [self validateNumber:string]; } - (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; break; } i++; } return res; }
还有一种方式,以下这种方式我还没有试过但是我找到了就分享出来吧:
1.定义常量以备使用
#define NUMBERS @"0123456789"2.进行以下操作
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string { NSCharacterSet*cs; cs = [[NSCharacterSetcharacterSetWithCharactersInString:NUMBERS] invertedSet]; NSString*filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; BOOLbasicTest = [string isEqualToString:filtered]; if(!basicTest) { UIAlertView* alert = [[UIAlertViewalloc] initWithTitle:@"提示" message:@"请输入数字" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; returnNO; } returnYES; }