隐藏搜索栏也隐藏了导航栏标题

时间:2016-08-29 11:24:28

标签: swift uinavigationbar

我有navigation bar search按钮。点击它会显示searchbar,点击取消按钮会隐藏它。但由于某些原因,如果隐藏searchbar,则导航栏标题视图也会隐藏。什么可能导致这个?起初我实际上希望它从右边滑入titleView,但我无法实现它,所以我就这样做了。

这是展示它并隐藏它的代码:

//Create searchbar
    func createSearchBar(){

        searchBar.showsCancelButton = true
        searchBar.tintColor = UIColor(red:0.184, green:0.996, blue:0.855, alpha:1.00)
        searchBar.placeholder = "Search brands"
        searchBar.delegate = self



        searchBar.hidden =  false
        searchBar.alpha = 0

        navigationItem.titleView = searchBar
        navigationItem.setLeftBarButtonItem(menuButton, animated: true)
        navigationItem.setRightBarButtonItem(searchButtton, animated: true)


        UIView.animateWithDuration(0.5, animations: {
            self.searchBar.alpha = 1
            }, completion: { finished in
                self.searchBar.becomeFirstResponder()
        })


    }

    //Searchbar hide
    func hideSearchBar() {


        navigationItem.setLeftBarButtonItem(menuButton, animated: true)
        navigationItem.setRightBarButtonItem(searchButtton, animated: true)
        searchBar.alpha = 0
        UIView.animateWithDuration(1, animations: {


            }, completion: { finished in

        })
    }

    //Searchbar cancel button
    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        hideSearchBar()
        searchBar.endEditing(true)
        snusBrandsTableView.reloadData()
    }

1 个答案:

答案 0 :(得分:4)

如果您希望隐藏title设置navigationItem searchBar,则需要将titleView设置为nil,然后设置标题。

func hideSearchBar() {
    navigationItem.setLeftBarButtonItem(menuButton, animated: true)
    navigationItem.setRightBarButtonItem(searchButtton, animated: true)
    searchBar.alpha = 0
    self.navigationItem.titleView = nil
    self.navigationItem.title = "YourTitle"
}