如何在UISearchController中更改UISearchBar的颜色

时间:2016-05-25 16:13:49

标签: ios swift uicollectionview uisearchbar uinavigationitem

我有一个UISearchBar,它是UISearchController的一部分,位于UICollectionViewController之上。我想改变UISearchBar的背景,这样它就是我选择的图像,而textfield的背景是半透明的。基本上,我想转此:

This is what it looks like with the given code

进入这个:

After

我已经尝试了我能在这里找到的一切。我尝试使用UISearchBarPosition和UIBarMetrics的每一个可能组合的searchBar.SetBackgroundImage,它们都不起作用。我达到的最好的是改变搜索的图标。这对我没有任何帮助。我认为这是因为它嵌入在UINavigationItem中。我不知道为什么它不起作用。这就是我设置的内容。

var resultSearchController:UISearchController? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let searchTable = storyboard!.instantiateViewControllerWithIdentifier("SearchTable") as! SearchTable
        resultSearchController = UISearchController(searchResultsController: searchTable)
        resultSearchController?.searchResultsUpdater = searchTable

        //Sets up the search bar and adds it to navigation header
        let searchBar = resultSearchController!.searchBar
        searchBar.searchBarStyle = UISearchBarStyle.Minimal
        searchBar.sizeToFit()
        searchBar.placeholder = "Find a Result"
        navigationItem.titleView = resultSearchController?.searchBar
               searchBar.setBackgroundImage(UIImage(named: "Horses.jpg"), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)

        resultSearchController?.hidesNavigationBarDuringPresentation = false
        resultSearchController?.dimsBackgroundDuringPresentation = true
        definesPresentationContext = true


    }

1 个答案:

答案 0 :(得分:0)

这是代码:

searchBar.setImage(UIImage(named: "Horses"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal);

var searchTextField: UITextField? = searchBar.valueForKey("searchField") as? UITextField
if searchTextField!.respondsToSelector(Selector("attributedPlaceholder")) {
    var color = UIColor.purpleColor()
    let attributeDict = [NSForegroundColorAttributeName: UIColor.purpleColor()]
    searchTextField!.attributedPlaceholder = NSAttributedString(string: "search", attributes: attributeDict)
}