简体   繁体   English

如何将 UISearchBar 图标更改为自定义图像?

[英]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?我 go 如何将搜索栏默认图标更改为自定义图像?

Way 1 : 方式1:

As luiyezheng answer, You can change the image of UISearchBar iCon. 作为luiyezheng的回答,你可以改变UISearchBar iCon的形象。

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

Search Icon image Change 搜索图标图像更改

屏幕截图

Way 2 : 方式2:

you can change tint color of Search iCon of UISearchBar iCon. 你可以改变UISearchBar iCon的搜索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 你可以使用setImage函数

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

Swift3 Swift3

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

luiyezheng 's answer works great. lyeyezheng的回答非常好。 The Swift 3 version of it is: 它的Swift 3版本是:

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

Swift 5 , iOS 13+ Swift 5 , iOS 13+

This is pretty easy, starting from iOS 13 UISearchBar has a .searchTextField property we may want to tweak somehow.这很简单,从 iOS 开始 13 UISearchBar有一个.searchTextField属性,我们可能想以某种方式进行调整。

Just set image view as its .leftView property, apply required tint color if needed.只需将图像视图设置为其.leftView属性,并在需要时应用所需的色调。

let image = UIImage(systemName: "location")
searchBar.searchTextField.leftView = UIImageView(image: image)
searchBar.searchTextField.leftView?.tintColor = .purple

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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