Edited by:
First change your type to textFiled keyBoard UIKeyboardTypeNumberPad , so your keyboard only has a numeric digit.
And give the tag UITextField that you want to apply to it (enter only a 4-digit number) , e.g.
textField.tag = 101; /// this is for, if you have multiple textFiled then it recognize that which textFiled have limit of 4 number ;
And use the following code method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(textField.tag != 101) return YES; if(string.length == 0) return YES; if(textField.text.length == 4) return NO; NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet]; if ([string rangeOfCharacterFromSet:nonNumberSet].location != NSNotFound) { return NO; } return YES; }
source share