Iphone UITextField only integer

前端 未结 9 679
借酒劲吻你
借酒劲吻你 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.

提交回复
热议问题