UINavigationBar:将SearchBar添加为TitleView

时间:2016-11-01 09:25:52

标签: ios uinavigationcontroller uinavigationbar uisearchbar uinavigationitem

我想添加uisearchbar代替控制器的标题。

我目前面临两个问题。

1) 我不知道这个灰色背景来自哪里。请查看此图片。 enter image description here

2)我也需要在其他内部屏幕中使用此搜索栏。但是当我推动另一个控制器时,这个搜索栏就被删除了。

这是我的代码:

// Seachbar Container View
    let searchBarContainer = ERView(frame: CGRectMake(0,0,280,44))
    searchBarContainer.autoresizingMask = [.FlexibleWidth]
    searchBarContainer.backgroundColor = UIColor.clearColor()

// Search Bar
    let searchBar = ERSearchBar(frame: searchBarContainer.bounds)
    searchBarContainer.addSubview(searchBar)

// Add View as Title View in Navigation Bar
    self.navigationController!.navigationBar.topItem?.titleView = searchBarContainer

这是我的UISearchBar类的代码

 func commonInit() -> Void {
    // Update UI

    if let searchField = self.valueForKey("searchField") as? UITextField{
        // To change background color
        searchField.backgroundColor = UIColor.appNavigationBarDarkRedColor()

        // Tint Color
        if let leftViewRef = searchField.leftView {
            leftViewRef.tintColor = UIColor.whiteColor()
        }else if let imgLeftView = searchField.leftView as? UIImageView{
            imgLeftView.tintColor = UIColor.whiteColor()
        }

        // Font Color
        searchField.font = UIFont.robotoRegularFont(WithSize: 14.0)

        // Text Color
        searchField.textColor = UIColor.whiteColor()

        // PlaceHolder Attributes
        searchField.attributedPlaceholder = NSAttributedString(string: "Search", attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()])
    }

    self.setImage(UIImage(named: "ic_search_white"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)
    // To change placeholder text color
}

请有人帮我。

1 个答案:

答案 0 :(得分:0)

For 1)将searchBarStyle属性设置为minimal。这将在UIsearchBar中不提供默认背景颜色。

2)我不太确定你的内心屏幕"是什么意思。但是如果你想要的是一个可以在不同视图控制器上工作的搜索栏,那么UISearchController就是你正在寻找的。 您可以使用Apple示例代码here