2016-10-27 186 views
0

我增加了搜索欄,以我的導航欄這樣全搜索欄添加到導航

searchBar.showsCancelButton = false 
    searchBar.placeholder = "Search" 
    searchBar.delegate = self 
    searchBar.enablesReturnKeyAutomatically = true 
    self.navigationItem.titleView = searchBar 

,但我有欄按鈕的項目有沒有辦法來掩蓋這一點,並讓搜索欄全長

+0

你檢查我的更新.....歡呼 – Joe

+0

對不起,我不能給予好評我沒有足夠的聲譽,但謝謝你 –

回答

0

試試這個代碼:

注:代碼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") 

    } 
} 

輸出:

enter image description here