Iphone UITextField only integer

前端 未结 9 707
借酒劲吻你
借酒劲吻你 2020-12-03 03:19

I have a UITextField in my IB and I want to check out if the user entered only numbers (no char)and get the integer value.

I get the integer value of the UITextField

9条回答
  •  时光说笑
    2020-12-03 04:20

    To only allow for numeric input:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { 
        return [string isEqualToString:@""] || 
            ([string stringByTrimmingCharactersInSet:
                [[NSCharacterSet decimalDigitCharacterSet] invertedSet]].length > 0);
    }
    

    To test for an integer:

    - (BOOL)isNumeric:(NSString *)input {
        for (int i = 0; i < [input length]; i++) {
            char c = [input characterAtIndex:i];
            // Allow a leading '-' for negative integers
            if (!((c == '-' && i == 0) || (c >= '0' && c <= '9'))) {
                return NO;
            }
        }
        return YES;
    }
    

提交回复
热议问题