In today's project, you only need to enter numbers in the text box. in xib, the Keyboard of UITextField is set to Number Pad, but the Keyboard switches back to another Keyboard to verify the content. Through the magic of Baidu, I know how to solve this problem through the following methods:
First, let the. xib viewController implement UITextFieldDelegate and associate it with the control to be verified.
Then paste the following code into the class.
- (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;}
There is another way. I have not tried the following method, but I will share it if I find it:
1. Define constants for future use
#define NUMBERS @"0123456789"
2. perform the following operations:
-(BOOL) textField :( UITextField *) textField shouldChangeCharactersInRange :( nsange) range replacementString :( NSString *) string {NSCharacterSet * cs; cs = [[NUMBERS: NUMBERS] invertedSet]; NSString * filtered = [string componentsSeparatedByCharactersInSet: cs] componentsJoinedByString: @ "]; BOOLbasicTest = [string isEqualToString: filtered]; if (! BasicTest) {UIAlertView * alert = [[UIAlertViewalloc] initWithTitle: @ "message: @" enter a number "delegate: nil cancelButtonTitle: @" OK "otherButtonTitles: nil]; [alert show]; returnNO;} returnYES ;}