How to change the color of the UISearchBar Icon? How to change the color of the UISearchBar Icon? ios ios

How to change the color of the UISearchBar Icon?


Best solution I found was hereChanging the color of the icons in a UItextField inside a UISearchBar

(This solution uses the original UISearchBar's icon, no need to supply your own graphical asset)

Converted to Swift (Swift 3):

    if let textFieldInsideSearchBar = self.searchBar.value(forKey: "searchField") as? UITextField,        let glassIconView = textFieldInsideSearchBar.leftView as? UIImageView {            //Magnifying glass            glassIconView.image = glassIconView.image?.withRenderingMode(.alwaysTemplate)            glassIconView.tintColor = .whiteColor    }


The searchIcon is located in the leftView of the searchTextField. Since this is accessible we can easily set the tintColor for the view. The tintColor is also used for the searchIcon.

So in your code you can change the search icon to white with the following code:

searchBar.searchTextField.leftView?.tintColor = .white


You can use a custom image of a white search icon, as the search bar will not modify your supplied image. To set a custom image, use this method. (Link to documentation.)

- (void)setImage:(UIImage *)iconImageforSearchBarIcon:(UISearchBarIcon)icon           state:(UIControlState)state;

Example Code:

[searchBar setImage:[UIImage imageNamed:@"SearchIcon"]   forSearchBarIcon:UISearchBarIconSearch              state:UIControlStateNormal];

In Swift:

searchBar.setImage(UIImage(named: "SearchIcon"), for: .search, state: .normal)