2016-07-26 92 views
2

我需要將導航控制器中搜索欄的方向設置爲中心。我有這個代碼創建的搜索欄編程:導航控制器swift中的中心搜索欄

lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(100, 40, 440, 40)) 

在viewDidLoad中:

searchBar.placeholder = "Search for Places" 
     var leftNavBarButton = UIBarButtonItem(customView:searchBar) 
     self.navigationItem.leftBarButtonItem = leftNavBarButton 

不過,我也有一個barButtonItem在左側。這已通過界面設置。

enter image description here

的問題是,當我通過代碼添加搜索欄,屏幕不會因爲它被覆蓋,顯示在下面的屏幕截圖顯示的按鈕。

enter image description here

我如何可以移動搜索欄,顯示菜單按鈕,然後在中心的搜索欄?

回答

4

的原因是你分配searchBarleftBarButtonItem,之所以它顯示在左邊,如果你在航海中心需要添加搜索到titleView導航欄,改變這種

 searchBar.placeholder = "Search for Places" 
    var leftNavBarButton = UIBarButtonItem(customView:searchBar) 
    self.navigationItem.leftBarButtonItem = leftNavBarButton 

lazy var searchBar:UISearchBar = UISearchBar(frame: CGRectMake(0, 0, 440, 40)) 
searchBar.placeholder = "Search for Places" 
self.navigationItem.titleView = searchBar // or use self.navigationcontroller.topItem?.titleView = searchBar 
+0

爲前看到此鏈接http://www.ioscreator.com/tutorials/customizing-navigation-bar-ios8-swift –

+0

完美地工作! –

2

您的搜索欄位於左側,因爲您正在設置左側導航按鈕。請嘗試更改titleView

let search = UISearchBar() // Create your search bar 
controller.navigationController.navigationItem.titleView = search