ios - 使用 XIB 的导航栏中的文本字段

标签 ios swift4.2

我正在尝试向导航栏添加一个文本字段以实现搜索功能。我不知道该怎么做。任何人都可以帮我做到这一点吗?

最佳答案

您可以按如下方式在导航栏中添加文本字段。

 extension UIViewController {

    func  setTextFieldInNavigationBar(withDelegate delegate: UITextFieldDelegate? = nil) {
      let txtField = UITextField(frame: CGRect(x: 0, y: 0, width: 120, height: 30))
      txtField.placeholder = "Enter some text"
      txtField.delegate = delegate

      //set other property as required
      navigationItem.titleView = txtField
  }

  //it will return UITextField, if there is TextField set in titleView in navigation bar
  var navTextField: UITextField? {
    return navigationItem.titleView as? UITextField
  }

}

您可以在 View Controller 中调用它,如下所示。

如果你想实现委托(delegate),那么使用这个...

setTextFieldInNavigationBar(withDelegate: self)

或者如果您不想实现委托(delegate),则使用此...

setTextFieldInNavigationBar()

您可以在UIViewController中按以下方式使用文本字段

print(navTextField?.text)

关于ios - 使用 XIB 的导航栏中的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376674/

相关文章:

swift - 没有这样的模块

ios - UITableView ScrollToRowAtIndexPath 方法不起作用

ios - 使用 DispatchQueue 索引超出范围异常

ios - 将 Parse 添加到 IOS 框架会导致问题吗?

ios - UIResponder didNotRecognizeSelector:应用程序因此错误而崩溃

swift - 按钮边框没有为暗模式选择合适的颜色

html - Swift:在标签中显示 HTML 数据不显示正确的图像

ios - TableView 不更新

ios - 导入 Monkeytalk 项目

ios - 如何创建委托(delegate)以在单击另一个 View Controller 的按钮时更改一个 View Controller 中的标签名称