我有一个程序,其中有四个文本字段,每个文本字段只能使用一个字符进行OTP。当用户在一个文本字段中输入一个字符时,它应自动移至下一个文本字段。但是由于某种原因,只有我的第一个文本字段才可以执行此操作,并且转到第三个文本字段,而不是第二个。并且文本字段的其余部分无法执行从一个文本字段移至另一文本字段的自动操作。我使用文本字段委托进行编码。下面给出的是我的代码。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (![string isEqualToString:@""]) {
    textField.text = string;
    if ([textField isEqual:self.firstOTP]) {
        [self.secondOTP becomeFirstResponder];
    }else if ([textField isEqual:self.secondOTP]){
        [self.thirdOTP becomeFirstResponder];
    }else if ([textField isEqual:self.thirdOTP]){
        [self.fourthOTP becomeFirstResponder];
    }else{
        [textField resignFirstResponder];
    }
    return NO;
}
return YES;
}

下面给出的是我的代码,用于识别是否输入了一个字符。
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (textField.text.length > 0) {
    textField.text = @"";
}
return YES;
}

任何人都可以识别该错误。

最佳答案

首先,确保为所有四个文本字段设置了delegate。另外,请确保您的插座连接正确。

接下来,将isEqual:的使用更改为==。实际上,您确实想在这里使用==,因为您想比较指针,而不是看这两个对象在逻辑上是否相等。

如果用户将文本粘贴到文本字段中,您也会遇到问题。用户可以轻松输入多个字符。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length > 0) {
        textField.text = [string substringToIndex:1];
        if (textField == self.firstOTP) {
            [self.secondOTP becomeFirstResponder];
        } else if (textField == self.secondOTP) {
            [self.thirdOTP becomeFirstResponder];
        } else if (textField == self.thirdOTP) {
            [self.fourthOTP becomeFirstResponder];
        } else {
            [textField resignFirstResponder];
        }

        return NO;
    }

    return YES;
}

07-28 03:45
查看更多