SearchBar how to change text color?

Here's what my search bar looks like

My search bar has gray text by default, but I want it to be white text. I can't figure out how to use swift to change the text color of the border, and you can't do that from a storyboard. The closest thing I've found

searchBarOutlet.setScopeBarButtonTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:UIControlState.Normal)

      

but alas, that won't work either. Any ideas?

+3


source to share


4 answers


It's a bit difficult to access the textbox inside the UISearchbar.

This is how it works:

for subView in self.searchBarOutlet.subviews
    {
        for secondLevelSubview in subView.subviews
        {
            if (secondLevelSubview.isKindOfClass(UITextField))
            {
                if let searchBarTextField:UITextField = secondLevelSubview as? UITextField
                {
                    //set the color here like this:
                    searchBarTextField.textColor = UIColor.redColor()
                    break;
                }

            }
        }
    }

      



Shorter solution:

var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField 
textFieldInsideSearchBar?.textColor = yourcolor

      

+10


source


// My preferred way of accessing searchField

if let searchTextField = self.searchBar.valueForKey("searchField") as? UITextField {

  searchTextField.textAlignment = NSTextAlignment.Left

}

      



+3


source


Swift 3

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white

      

+2


source


In my case for swift 3.0

(mySearchBar.value (forKey: "searchField") like? UITextField) ?. textColor = UIColor.white

0


source







All Articles