我在一个静态的tableviewcontroller控制器中有几个UITextFields。我为每个文本字段指定了一个标记值,以便当用户单击键盘上的next时,我可以获得具有下一个标记的文本字段,并调用becomesFirstResponder,以便用户可以在文本字段之间导航。
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let tag = textField.tag
if let tf = self.view.viewWithTag(tag + 1) as? UITextField {
tf.becomeFirstResponder()
}
}这基本上是可行的。但是,当我使用ReactiveKit/Bond时,特别是当我在viewdidload中调用以下行(假设lastName是下一个文本字段)来绑定UI和模型时:
profile.lastName.bidirectionalBind(to: lastName.reactive.text)下一个文本字段(lastName)将在几毫秒内变为编辑模式,然后键盘被清除,文本字段不再处于编辑模式。
当我注释掉键合线时,逻辑就会成功。我尝试将双向绑定替换为单向绑定,或者调用obserNext,但这也会导致相同的问题。
发布于 2018-02-09 20:18:45
经过一段时间的搜索、调试和尝试之后,我将调用becomeFirstResponder的代码行改为异步分派,具有讽刺意味的是,这使得它可以工作。然而,我不知道为什么。我在答案here中找到了这个解决方案(针对不同的反应库)。
更新的代码:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let tag = textField.tag
if let tf = self.view.viewWithTag(tag + 1) as? UITextField {
DispatchQueue.main.async {
tf.becomeFirstResponder()
}
}
}发布于 2018-02-09 04:09:57
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let tf = self.view.viewWithTag(textField.tag + 1) as? UITextField {
tf.becomeFirstResponder()
return false
}
return true
}试试这段代码。您不需要在当前textField上显式调用resignFirstResponder()。调用becomeFirstResponder()应该就足够了。
https://stackoverflow.com/questions/48693662
复制相似问题