我正在尝试向导航栏添加一个文本字段以实现搜索功能。我不知道该怎么做。任何人都可以帮我做到这一点吗?
最佳答案
您可以按如下方式在导航栏中添加文本字段。
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/