試試這個代碼:
注:代碼barButton隱藏功能更新時,搜索欄是活動的,回來的時候取消按鈕按下。
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")
}
}
輸出:

來源
2016-10-27 21:46:04
Joe
你檢查我的更新.....歡呼 – Joe
對不起,我不能給予好評我沒有足夠的聲譽,但謝謝你 –