在 swift 中用搜索栏替换后如何将 self.navigationItem.titleView 放入标题
How to put self.navigationItem.titleView with title after replace it with searchbar in swift
我有搜索栏,当点击图片时,它会在顶部导航创建搜索栏,替换为标题。然后当在搜索栏外点击时,标题不再显示,它仍然带有搜索栏(文本字段),如果在搜索栏外点击或点击如何再次显示标题?
这是在顶部导航创建搜索栏的代码,替换为标题。
func createSearchBar(){
searchBar.sizeToFit()
searchBar.showsCancelButton = false
searchBar.placeholder = "Enter key"
searchBar.delegate = self
self.navigationItem.titleView = searchBar
}
这是点击搜索栏外部时的代码
extension ViewCon {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewCon.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
self.searchBar.resignFirstResponder()
self.navigationController?.navigationBar.topItem?.title="Title List"
}
}
但是我要如何再次在顶部导航中显示标题?
您需要将 nil
self.navigationItem.titleView = nil
参见:https://developer.apple.com/reference/uikit/uinavigationitem/1624935-titleview
我有搜索栏,当点击图片时,它会在顶部导航创建搜索栏,替换为标题。然后当在搜索栏外点击时,标题不再显示,它仍然带有搜索栏(文本字段),如果在搜索栏外点击或点击如何再次显示标题?
这是在顶部导航创建搜索栏的代码,替换为标题。
func createSearchBar(){
searchBar.sizeToFit()
searchBar.showsCancelButton = false
searchBar.placeholder = "Enter key"
searchBar.delegate = self
self.navigationItem.titleView = searchBar
}
这是点击搜索栏外部时的代码
extension ViewCon {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewCon.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
self.searchBar.resignFirstResponder()
self.navigationController?.navigationBar.topItem?.title="Title List"
}
}
但是我要如何再次在顶部导航中显示标题?
您需要将 nil
self.navigationItem.titleView = nil
参见:https://developer.apple.com/reference/uikit/uinavigationitem/1624935-titleview