ios - 防止 UITextField 在更改 firstResponder 时取值

标签 ios swift uitextfield resignfirstresponder becomefirstresponder

我有四个 UITextField,每个代表 OTP 的一个数字。我希望控件在用户输入代码时转移到连续的文本字段。我的实现如下。

extension FillSignUpCodeController: UITextFieldDelegate {

    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = ""
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let inputString = (textField.text! as NSString).replacingCharacters(in: range, with: string)

        if inputString.count == 1 {
            switch textField {

            case textFieldCodeFirstDigit:
                textFieldCodeFirstDigit.text = inputString
                textFieldCodeFirstDigit.resignFirstResponder()
                textFieldCodeSecondDigit.becomeFirstResponder()

            case textFieldCodeSecondDigit:
                textFieldCodeSecondDigit.text = inputString
                textFieldCodeSecondDigit.resignFirstResponder()
                textFieldCodeThirdDigit.becomeFirstResponder()

            case textFieldCodeThirdDigit:
                textFieldCodeThirdDigit.text = inputString
                textFieldCodeThirdDigit.resignFirstResponder()
                textFieldCodeFourthDigit.becomeFirstResponder()

            case textFieldCodeFourthDigit:
                textFieldCodeFourthDigit.text = inputString
                textFieldCodeFourthDigit.resignFirstResponder()

            default:
                return false
            }
        }
        return true
    }
}

在这段代码中,当用户键入第一个数字时,第一个文本字段获取输入值并将控件移动到下一个文本字段。但是,第二个文本字段采用第一个数字的值。我尝试在更改 firstResponder 后将文本设置为空,但它不起作用。我该如何解决这个问题?谢谢。

最佳答案

由于 textField(_:shouldChangeCharactersIn:replacementString:) 在文本出现在文本字段中之前 执行,您应该将代码放在一个方法中,当文本已经更改

您应该观察文本字段的变化并在那里执行响应程序更改代码。您可以找到更多相关信息 in this question .

此外,在更改第一响应者之前辞职是多余的,您不需要这样做。

单独处理每个文本字段也是非常多余的。我建议将您的文本字段包含在一个数组中并遍历它们。

关于ios - 防止 UITextField 在更改 firstResponder 时取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47770969/

相关文章:

ios - UITextField attributedPlaceholder 颜色和不透明度在 swift 4

ios - UIButton 具有可与 UIViewPropertyAnimator 互插的动画

ios - Firebase 按日期对数据排序

ios - 如何将 NSURLSessionConfiguration 配置到 NSObject 类中?

ios - 在应用商店更新应用版本时更改关键字或添加新关键字

swift - '[<UIProxyObject> 设置值 :forUndefinedKey:]: this class is not key value coding-compliant for the key containerView

iphone - 在 View 弹出之前存储 UITextField 内容

ios - UIAlertViewController 添加文本字段委托(delegate)

ios - 将 3 种不同的信息加载到 3 种不同类型的细胞

ios - 以编程方式将 UINavigationBar 添加到 UIView?