How to change text color of PlaceHolder in UISearchBar? (iOS 13)
As you already mentioned, your code works only in viewDidAppear
, which makes the placeholder to flicker from the default gray color to the preferred color.
However, there seem to be a time before viewDidAppear
(I couldn't figure it out when exactly), to change the placeholder before the view actually appears.
I suppose, this may be connected to how iOS handles light/dark mode and/or an iOS bug.
The solution I came out with that works around the issue:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if #available(iOS 13.0, *) {
let placeholder = NSAttributedString(string: "Search",
attributes: [
.foregroundColor: UIColor.white
])
let searchTextField = searchBar.searchTextField
// Key workaround to be able to set attributedPlaceholder
DispatchQueue.global().async {
DispatchQueue.main.async {
searchTextField.attributedPlaceholder = placeholder
}
}
}
}
There seem to be no performance and/or other downside to this method.
If anybody else comes with a better approach, feel free to collaborate.