Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the color of the UISearchBar Icon?

I don't know how to modify the original searchIcon's color.

enter image description here

like image 784
Damien Romito Avatar asked Nov 19 '14 10:11

Damien Romito


3 Answers

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
like image 198
Milander Avatar answered Nov 14 '22 12:11

Milander


Best solution I found was here Changing 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
    }
like image 43
raf Avatar answered Nov 14 '22 13:11

raf


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 *)iconImage
forSearchBarIcon:(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)
like image 33
Federica Venuto Avatar answered Nov 14 '22 12:11

Federica Venuto