Queen Solutions Queen Solutions - 4 months ago 29
iOS Question

how to make text field that to accept only 4 digit or numbers in iphone

I have an app in which I want to enter a numeric value in

. But I want to allow only 4 digits to be entered. So 1234 would be valid but 12345 cannot be entered. Any idea how how I can modify this to accept only a numeric value limited to 4 digits?


Sample Code :

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    NSString *currentString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    int length = [currentString length];
    if (length > 4) {
       return NO;
    return YES;