简体   繁体   English

导航控制器中的中心搜索栏

[英]Center search bar in navigation controller swift

I need to change the orientation of a search bar in a navigation controller to be set to the center. 我需要在导航控制器中将搜索栏的方向更改为设置为中心。 I have created the search bar programmatically with this code: 我已使用以下代码以编程方式创建了搜索栏:

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

and in viewDidLoad: 并在viewDidLoad中:

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

However I also have a barButtonItem in the left. 但是我在左侧也有一个barButtonItem。 This has been set through the interface. 这已通过界面设置。

在此处输入图片说明

The issue is that when I add the search bar through the code, the screen does not display the button as it gets covered as shown in the screenshot below. 问题是,当我通过代码添加搜索栏时,屏幕不显示该按钮,因为该按钮被覆盖了,如下面的屏幕快照所示。

在此处输入图片说明

How can I shift the search bar to show the menu button followed by the search bar in the center? 如何移动搜索栏以显示菜单按钮,然后在中心显示搜索栏?

the reason are you assigned the searchBar to leftBarButtonItem that the reason it shows in left side , if you need in center of Navigation add your search to titleView for navigation bar, change this 原因是你指定的searchBar ,以leftBarButtonItem它显示在左边,如果你在航海中心需要添加搜索到的原因titleView导航栏,更改此

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

to

 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

Your search bar is on the left because you're setting left navigation button. 您的搜索栏位于左侧,因为您要设置左侧导航按钮。 Try to change titleView instead. 尝试改为更改titleView

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM