简体   繁体   中英

Textfield in navigation bar using an XIB

I am trying to add a textfield to navigation bar for search functionality. I don't have any idea how to do this. Can any one help me to do this?

You can add textfield in navigation bar as follow.

 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
  }

}

You can call this in view controller as follow.

If you want to implement delegate then use this...

setTextFieldInNavigationBar(withDelegate: self)

or if you do not want to implement delegate then use this...

setTextFieldInNavigationBar()

You can use textfield in following way in UIViewController

print(navTextField?.text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM