SearchBar, how to change text color?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 15:13:28

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
// My preferred way of accessing searchField

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

  searchTextField.textAlignment = NSTextAlignment.Left

}

Swift 3

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

In my case for swift 3.0

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

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