简体   繁体   中英

How to detect number length in UITextField?

There is a UITextField with name numbercontent , after entering 8 numbers, it will automatically call the next function. Following is my code

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
 if (self.numbercontent.text.length == 7) {
  [self.numbercontent resignFirstResponder];
  [self stopFly];
 }
 return YES;
}

But there's a bug

when I enter the 8th number, it will automatically call the next function, but the 8th number isn't shown in the UITextField.

If Change self.numbercontent.text.length == 7 to self.numbercontent.text.length > 7 , the 8th number is shown in the UITextField, but I need to enter one more number to call the next function, how to fix this bug, thanks.

Try this, instead of shouldChangeCharactersInRange ,

[_txtNum addTarget:self action:@selector(didChangeText:) forControlEvents:UIControlEventEditingChanged];

and then add this method,

-(void)didChangeText:(UITextField*)sender
{
    if(sender.text.length==8)
    {
        [self stopFly];
        [self.txtNum resignFirstResponder];
    }
}

Although answer suggested by @DhavalBhimani is the standard way to handle this, but alternatives can be used with current approach like:

In Objective-C:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *updatedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField.text.length == 7) {
        textField.text = updatedString;
        [textField resignFirstResponder];
        [self stopFly];
    }
    return YES;
}

In Swift 4.0:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let updatedString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string)
    if textField.text?.count == 7 {
        textField.text = updatedString
        self.view.endEditing(true)
    }
    return true
}

Use this.

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


// _textLenghtLimit = your text max lenght
    if (_textLenghtLimit > 0) {
        if ((range.location >= _textLenghtLimit || textField.text.length + 1 > _textLenghtLimit) && range.length == 0) {
            return NO;
        }
    }
    return YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM