I have an app in which I want to enter a numeric value in UITextField. 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;
}
Swift 3.0 Xcode 8.3.3...
First UITextField set the delegate and then put this code...
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let textstring = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let length = textstring.characters.count
    if length > 4 {
        return false
    }
    return true
}
Objective C Code...
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
      {
        NSString *textstring = [textField.text stringByReplacingCharactersInRange:range withString:string];
        int length = [textstring length];
        if (length > 4) {
           return NO;
        }
            return YES;
      }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With