自动检查文本字段长度并点击方法 UITextfield

Auto check textfield length and Hit a method UITextfield

您好,我需要输入手机号码并验证手机文本字段范围应为 10。 当文本字段值 ==10 时,我需要在 mobile textfield.text 长度变为 10 时调用一个函数。 我下面的代码工作正常,但我需要再按 1 个字符(表示 11)才能调用它。 请问我是怎么解决的

#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField) 
   {


        if (textField.text.length >= MAX_LENGTH && range.length == 0)
        {

            if (textField.text.length==MAX_LENGTH) 
            {

                NSLog(@“Want to call Call method HERE ");

            }


            return NO; // return NO to not change text
        }


    }
     return YES;
}

shouldChangeCharactersInRange 在实际文本更改之前调用。如果您想在实际文本更改后执行操作,您可以尝试以下方法:

...
//start observing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textHasChanged:) name:UITextFieldTextDidChangeNotification object:{your UITextField}];
...

- (void)textHasChanged:(NSNotification *)notification {
    UITextField *textField = [notification object];
    //check if textField.text.length >= 10
    //do stuff...
}

请尝试使用以下代码 -

#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField==user_mobile_txtField) 
   {


        if (textField.text.length >= MAX_LENGTH )
        {

            if (textField.text.length==MAX_LENGTH) 
            {

                NSLog(@“Want to call Call method HERE ");

            }


            return NO; // return NO to not change text
        }


    }
     return YES;
}

你可以通过stringByReplacingCharactersInRange:withString:

方法获取字符改变后的字符串
#define MAX_LENGTH 10

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == user_mobile_txtField) {
        NSString *fullString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        if (fullString.length >= MAX_LENGTH && range.length == 0) {
            if (fullString.length == MAX_LENGTH) {
                NSLog(@“Want to call Call method HERE ");
            }
            return NO; // return NO to not change text
        }
    }
    return YES;
}