如何检测UITextField中的数字长度?

时间:2018-04-11 15:53:04

标签: ios objective-c uitextfield

有一个名为numbercontent的UITextField,在输入8个数字后,它会自动调用下一个函数。以下是我的代码

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

但是有一个错误

当我输入第8个数字时,它会自动调用下一个函数,但第8个数字不会显示在UITextField中。

如果将self.numbercontent.text.length == 7更改为self.numbercontent.text.length > 7,则第8个数字会显示在UITextField中,但我需要再输入一个数字来调用下一个函数,如何修复此错误,谢谢。

3 个答案:

答案 0 :(得分:0)

试试这个,而不是shouldChangeCharactersInRange

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

然后添加此方法,

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

答案 1 :(得分:0)

尽管@DhavalBhimani建议的答案是处理此问题的标准方法,但替代方案可以与当前方法一起使用,如:

在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;
}

在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
}

答案 2 :(得分:0)

使用此功能。

- (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;
}