今天項目中有個文本框需要只可以輸入數字的需求,首先在.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; }