Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SearchBar, how to change text color?

Here's what my search bar looks like

My search bar has default gray text, but I want it to be white text. I can't figure out how to use swift to change the scope bar text color, and you are unable to do it from storyboard. The closest I've found is

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

but alas this won't work either. Any ideas?

like image 260
36 By Design Avatar asked Dec 01 '22 15:12

36 By Design


1 Answers

Its a little hard to access the Textfield 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
like image 148
Dejan Skledar Avatar answered Dec 12 '22 03:12

Dejan Skledar