如何通过单击按钮将焦点设置到视图中的下一个TextField?

时间:2018-06-21 23:17:36

标签: ios swift

有很多人遇到了iOS数字键盘缺少 Done 按钮的问题,并且有很多解决方案。我创建了此按钮,但找不到通过按此按钮将焦点设置在下一个文本字段上的方法。在我的情况下,有使用TableViewCells生成Table的代码。这就是为什么要创建对每个单元格(无论如何有很多单元格)的引用的普遍想法。每个TableViewCell包括ContentView,而ContentView包括TextField。 结果,我的自定义 Done 按钮的行为应类似于标准键盘中的Return按钮。顺便说一句, textFieldShouldReturn 中的方法可以改变焦点,但是 textFieldShouldReturn 可以在内置的 Return < / em>按钮。 附言我是Swift的新手。

2 个答案:

答案 0 :(得分:1)

注意:我创建了一个示例项目,其中实现了下一个按钮的功能。您可以找到项目:https://github.com/nasirky/uitableview-form

您可以将带有完成按钮的工具栏添加到UITextField inputAccessoryView 。这是一个例子

override func viewDidLoad() { 
  super.viewDidLoad()
  textField.inputAccessoryView = getToolbar() 
  } 

func getToolbar() -> UIToolbar {
   let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 40))
  let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action:#selector(doneAction(_:)))
  toolBar.setItems([doneButton], animated: false) 
  return toolBar 
}

func doneAction(_ sender: UIBarButtonItem) {
 /* Code for dismissing keyboard or moving focus to next UITextField */
}

答案 1 :(得分:0)

仔细检查了现有的跳转功能后,将其放入了 textFieldDidEndEditing 事件中。在Done函数内部(在Nasir的示例中为doneAction),我放入了 self.endEditing(true)