Iphone UITextField only integer

前端 未结 9 576
借酒劲吻你
借酒劲吻你 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:09

    Implementing shouldChangeCharactersInRange method as below does not allow the user input non-numeric characters.

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

    This returns YES if the string is numeric, NO otherwise. the [string isEqualToString@""] is to support the backspace key to delete.

    I love this approach because it's clean.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-03 04:22

    You could also use UITextFieldDelegate method

    textField:shouldChangeCharactersInRange:replacementString:

    to live check that each time the user press a key, it is a simple digit, so that he/she knows that only int value is to be entered in the field.

    0 讨论(0)
提交回复
热议问题