Queen Solutions Queen Solutions - 1 year ago 104
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?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download