2016-10-27 188 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