SearchBar, how to change text color?

偶尔善良 提交于 2019-12-21 20:27:28

问题


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?


回答1:


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



回答2:


// My preferred way of accessing searchField

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

  searchTextField.textAlignment = NSTextAlignment.Left

}



回答3:


Swift 3

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



回答4:


In my case for swift 3.0

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



来源:https://stackoverflow.com/questions/26284658/searchbar-how-to-change-text-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!