Kamen Dobrev
Kamen Dobrev

Reputation: 1371

Changing textColor for searchTextField

I have UISearchController and I want to change the textColor of the search field.

For my surprise

searchController.searchBar.searchTextField.textColor = .red

did not change the color of the search field, also none of this worked:

   searchController.searchBar.searchTextField.attributedText = NSAttributedString(string: "test", attributes: [NSAttributedString.Key.foregroundColor: UIColor.red]
   searchController.searchBar.searchTextField.tintColor = .red
   UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = .red

The only thing that worked for me is

searchController.searchBar.searchTextField.delegate = self
....
func textFieldDidBeginEditing(_ textField: UITextField) // became first responder
{
    //textField's textColor is white for some reason
    textField.textColor = .red
}

I guess this must be something specific to my project. Is there anyone else having the same problem?

Upvotes: 0

Views: 238

Answers (1)

Protocol
Protocol

Reputation: 1792

Use following code. It will work

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {
 textfield.textColor = UIColor.red
}

Upvotes: 1

Related Questions