gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 10:47:49 24 4
gpt4 key购买 nike

我有四个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com