IOS Development limits UITextField to only numbers

Source: Internet
Author: User

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 ;}




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.