0
votes

I got these code lines in my view controller.

this code is for UISearchBar text color and it works

let textFieldInsideSearchBar = searchBar.value(forKey: “searchField”) as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.white

this code is for UISearchBar placeholder text color and it doesn't work

let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: “placeholderLabel”) as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.white

this is the working code for placeholder text color and etc.

this code is for UISearchBar magnifying glass icon color and it works

let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
glassIconView?.tintColor = UIColor.white

this code is code for UISearchBar clear button (x) color and it doesn't work

let clearButton = textFieldInsideSearchBar?.value(forKey: “clearButton”) as! UIButton
clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
clearButton.tintColor = UIColor.white

I have find out that that version of clear button color change doesn't work at Xcode 11. Managed to have working version. You have to import asset for cancel button. After that you need to change "Render As" attribute of your icon to Template Image at Assets folder.

let clearButton = textFieldInsideUISearchBar?.value(forKey: "clearButton") as! UIButton
    clearButton.setImage(UIImage(named: "yourIconName"), for: .normal)
    clearButton.tintColor = .white

Besides i have tried nearly every code that I can find. Somehow they work for text and magnifying glass but doesn't work for other two. They look very ugly when the background is dark. Is there any better way to change colors of clear button and placeholder text ?

Xcode version 11.1 Swift 5.1

2
Refer this for Placeholder colorudbhateja
this works for placeholder color thanks ! although clear button is still not workingF.Fleur

2 Answers

0
votes

For placeholder color, refer to this.

To change search bar clear image tint color, you need to set SearchBar with new images.

    yourSearchBar.setImage(normalImage, for: .clear, state: .normal)
    yourSearchBar.setImage(highlightedImage, for: .clear, state: .highlighted)
0
votes

UISearchBarController customisation for iOS 13 try this