我正在像这样向我的导航栏添加一个搜索栏
searchBar.showsCancelButton = false
searchBar.placeholder = "Search"
searchBar.delegate = self
searchBar.enablesReturnKeyAutomatically = true
self.navigationItem.titleView = searchBar
但是我有条形按钮项有没有办法隐藏它并使搜索栏全长
最佳答案
试试这个代码:
注意:代码更新了 barButton 在 searchBar 处于事件状态时隐藏功能,并在按下取消按钮时返回。
class ViewController: UIViewController,UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {
var resultSearchController : UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.resultSearchController = UISearchController(searchResultsController: nil)
self.resultSearchController.searchResultsUpdater = self
self.resultSearchController.delegate = self
self.resultSearchController.searchBar.delegate = self
self.resultSearchController.hidesNavigationBarDuringPresentation = false
self.resultSearchController.dimsBackgroundDuringPresentation = true
self.definesPresentationContext = true
self.navigationItem.titleView = resultSearchController.searchBar
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))
}
func updateSearchResults(for searchController: UISearchController) {
// You have to implement search delegate method here to make it work.
if resultSearchController.isActive == true {
self.navigationItem.rightBarButtonItem = nil
} else {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Your Button", style: .plain, target: self, action: #selector(addTapped))
}
}
func addTapped() {
// You can do your stuff here. when your button pressed...
print("Button Pressed")
}
}
输出:
关于ios - 将完整的搜索栏添加到导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290095/