简体   繁体   中英

Possible to change the text color within a search bar while it is displayed?

I'm trying to display an initial prompt message within a search bar in one color, then as soon as the user starts to enter text remove the prompt and change the color of the text the user is entering.

I'm using this to set the initial color of the prompting message

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.lightGrayColor()

Then when I get notified the user has started to enter text I attempt to change the color

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) 
{
    appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).textColor = UIColor.blackColor()
    ...

It seems the color can only be set before the search bar is displayed, not once it is already displayed. Anybody know any workarounds for this?

(Search bar is being created & displayed automatically via UISearchController)

Use UISearchBar 's placeholder property to set the initial prompt message. UISearchBar will set its color to 70% gray by default, entirely independent from the text color for user-entered text.

var searchBar = UISearchBar()
// This message will be set to a gray color by default 
// UISearchBar will automatically clear it once the user starts typing
searchBar.placeholder = "Enter a message here..."
// This text color will be applied to the text that the user types
searchBar.textColor = UIColor.blackColor()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM