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

问题描述 投票:0回答:1

我正在尝试将文本字段添加到导航栏以实现搜索功能。我不知道该怎么做。谁能帮助我做到这一点?

ios swift4.2
1个回答
0
投票

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

 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
  }

}

您可以按如下方式在视图控制器中调用它。

如果要实现委托,请使用此...

setTextFieldInNavigationBar(withDelegate: self)

或者如果您不想实现委托,请使用此...

setTextFieldInNavigationBar()

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

print(navTextField?.text)
© www.soinside.com 2019 - 2024. All rights reserved.