2016-07-26 34 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