如何在UINavigationBar中为UIsearchBar设置scopeBar和cancelButton

时间:2017-10-19 19:48:41

标签: swift swift3 uinavigationcontroller

我有一个带导航栏的viewController,我试图将一个UISearchBar放在navBar中。它显然不像我想象的那么简单。

以下是我目前的代码:

private func setupNavigationBarItems(){
    self.navigationItem.titleView = searchBar

    searchBar.placeholder = "Search Users + Songs"

    navigationController?.navigationBar.tintColor = UIColor(red: 20/255, green: 20/255, blue: 20/255, alpha: 1)
    navigationController?.navigationBar.isTranslucent = false
}

func setupSearchBar() {
    self.searchBar.delegate = self
    self.searchBar.barStyle = UIBarStyle.blackTranslucent
    self.searchBar.searchBarStyle = .minimal
    self.searchBar.placeholder = "Search songs + users"
    self.searchBar.backgroundColor = .clear        
    self.searchBar.backgroundImage = nil
    self.searchBar.showsScopeBar = false
    self.searchBar.scopeBarBackgroundImage = UIImage.imageWithColor(color: .clear)
    UISegmentedControl.appearance().backgroundColor = .clear
    UISegmentedControl.appearance().tintColor = UIColor(red: 20/255, green: 40/255, blue: 60/255, alpha: 1)
}

lazy var searchBar: UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 200, height: 20))

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
    UIView.animate(withDuration: 0.5) {
        self.view.layoutIfNeeded()
        self.searchBar.setShowsCancelButton(true, animated: true)

        self.searchBar.showsScopeBar = true
        self.searchBar.scopeButtonTitles = ["Songs", "Users"]
        self.searchBar.selectedScopeButtonIndex = 0
        self.searchBar.sizeToFit()
        self.searchBar.frame.size.width = 335
    }
}

这会使searchBar出现在navBar中,但这就是全部。取消按钮不显示,并且scopeBar在执行didBeginEditing时也不显示。如何获取scopeBar和取消按钮以显示在navBar中?

0 个答案:

没有答案