How to check text field input at real time?

前端 未结 7 1660
Happy的楠姐
Happy的楠姐 2020-12-09 21:07

I am writing validation for my textfield, I found something interesting that whether I can check how many digits I am typing into the textfield at real time. My text field i

7条回答
  •  借酒劲吻你
    2020-12-09 21:42

    Set up a delegate for the UITextField and implement the method – textField:shouldChangeCharactersInRange:replacementString: Details and examples are in the UITextFieldDelegate Protocol Reference, but here's a quick example:

    - (BOOL)textField:(UITextField *)textField 
    shouldChangeCharactersInRange:(NSRange)range 
    replacementString:(NSString *)string
    {
            NSString *text = [textField text];
            // NOT BACKSPACE
            if ([string length] || text.length + string.length < 8) {
                return YES;
            } else if (text.length + string.length > 8) {
                return NO;
            } else {
                    // DO SOMETHING FOR LENGTH == 8
                    return YES;
            }
    }   
    

提交回复
热议问题