简体   繁体   中英

How to change UISearchBar Icon to custom image?

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

截屏

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

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

屏幕截图

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

屏幕截图

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM