在viewDidLoad之后的navigationBar中添加searchBar?

时间:2015-01-29 23:10:41

标签: ios swift uinavigationbar uisearchdisplaycontroller

在我的应用程序中,我想在导航栏中有一个搜索按钮,当按下按钮时,搜索栏应该出现在导航栏中。我已经看过很多关于这个主题的帖子,但不知何故它对我不起作用。 所以,我在导航栏下面放了一个SearchDisplayController。然后在viewDidLoad我为搜索按钮分配一个动作并从superview中删除搜索栏。单击按钮后,我正在调用mapSearchDisplayController.displaysSearchBarInNavigationBar = true,但没有任何事情发生。代码摘录如下:

    override func viewDidLoad() {
            super.viewDidLoad()

            banner.delegate = self

            // Add button to navbar
            var filterButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: nil)
            self.navigationItem.leftBarButtonItem = filterButton

            var aboutButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "aboutAction")
            var searchButton : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: "searchAction")
            var rButtons : [UIBarButtonItem] = [aboutButton, searchButton]
            self.navigationItem.rightBarButtonItems = rButtons


            // Deal with Search Display Controller
            self.mapSearchDisplayController.delegate = self.mapSearchDisplayController;
            self.mapSearchDisplayController.searchResultsDataSource = self.mapSearchDisplayController;
            self.mapSearchDisplayController.searchResultsDelegate = self.mapSearchDisplayController;
            self.mapSearchDisplayController.searchBar.removeFromSuperview();
}
    func searchAction(){
            println("Search action")
            mapSearchDisplayController.displaysSearchBarInNavigationBar = true
        }

如果我在displaysSearchBarInNavigationBar = true中致电viewDidLoad,则searchBar会在导航栏中正确显示。 如何在按下按钮的导航栏中显示? 任何帮助都是适用的。

1 个答案:

答案 0 :(得分:0)

我使用

创建了一个搜索栏
let searchBar = UISearchBar(frame : CGRect(0, 0, self.navigationController?.navigationBar.frame.size.width)! * 0.9, 0)

self.searchBar.placeholder = "Search"
self.searchBar.delegate = self

然后将其添加到导航栏,如下所示:

self.navigationItem.titleView = self.searchBar

还可以进行更多造型等,但我刚创建并将其添加到按钮上的导航栏中,并在需要隐藏时将其从superview中删除。