How to change UISearchBar Icon to custom image?
Asked Answered
V

4

19

Currently, I have the default magnifying glass as my search bar icon. However, I want to put a custom image in its place, particularly this image:

Custom Arrow Icon

Screen Shot

How would I go about changing the search bar default icon to the custom image?

Voroshilovsk answered 14/6, 2016 at 7:35 Comment(0)
H
34

you can use setImage function

 searchBar.setImage(UIImage(named: "your image"), forSearchBarIcon: .Search, state: .Normal)

Swift3

searchBar.setImage(UIImage(named: "Image Name"), for: .search, state: .normal)
Hone answered 14/6, 2016 at 7:46 Comment(0)
L
18

Way 1 :

As luiyezheng answer, You can change the image of UISearchBar iCon.

UISearchBar.appearance().setImage(UIImage(named: "new_search_icon"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)

Search Icon image Change

screen shot

Way 2 :

you can change tint color of Search iCon of UISearchBar iCon.

let textFieldInsideSearchBar = searchBarCustom.valueForKey("searchField") as? UITextField
let imageV = textFieldInsideSearchBar?.leftView as! UIImageView
imageV.image = imageV.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
imageV.tintColor = UIColor.purpleColor()

Output :

Search Icon image tint color change

screen shot

Legislation answered 30/8, 2016 at 6:22 Comment(1)
With Swift 4.2: imageV.image = imageV.image?.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)Matthaus
P
2

luiyezheng's answer works great. The Swift 3 version of it is:

searchBar.setImage(UIImage(named: "Image Name"), for: .search, state: .normal)
Pitzer answered 26/9, 2017 at 3:50 Comment(0)
C
2

Swift 5, iOS 13+

This is pretty easy, starting from iOS 13 UISearchBar has a .searchTextField property we may want to tweak somehow.

Just set image view as its .leftView property, apply required tint color if needed.

let image = UIImage(systemName: "location")
searchBar.searchTextField.leftView = UIImageView(image: image)
searchBar.searchTextField.leftView?.tintColor = .purple
Chardin answered 30/1, 2023 at 0:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.