简体   繁体   English

如何更改 UISearchBar 图标的颜色?

[英]How to change the color of the UISearchBar Icon?

I don't know how to modify the original searchIcon 's color.我不知道如何修改原始searchIcon的颜色。

在此处输入图片说明

Best solution I found was here Changing the color of the icons in a UItextField inside a UISearchBar我找到的最佳解决方案是更改 UISearchBar 内 UItextField 中图标的颜色

(This solution uses the original UISearchBar's icon, no need to supply your own graphical asset) (本方案使用原UISearchBar的图标,无需提供自己的图形资源)

Converted to Swift (Swift 3):转换为 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. searchIcon 位于 searchTextField 的 leftView 中。 Since this is accessible we can easily set the tintColor for the view.由于这是可访问的,我们可以轻松地为视图设置 tintColor。 The tintColor is also used for the searchIcon. tintColor 也用于 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 *)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)

This soultion worked for me on Xcode 8.2.1 in Swift 3.0.这个灵魂在 Swift 3.0 中的 Xcode 8.2.1 上对我有用。 :

extension UISearchBar
{
    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }

    func setMagnifyingGlassColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
        glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
        glassIconView?.tintColor = color
    }
}

Usage example:用法示例:

searchController.searchBar.setPlaceholderTextColorTo(color: mainColor)
searchController.searchBar.setMagnifyingGlassColorTo(color: mainColor)

Swift-3:斯威夫特-3:

extension UISearchBar
{

    func setMagnifyingGlassColorTo(color: UIColor)
    {
        // Search Icon
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView
        glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
        glassIconView?.tintColor = color
    }

    func setClearButtonColorTo(color: UIColor)
    {
        // Clear Button
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let crossIconView = textFieldInsideSearchBar?.value(forKey: "clearButton") as? UIButton
        crossIconView?.setImage(crossIconView?.currentImage?.withRenderingMode(.alwaysTemplate), for: .normal)
        crossIconView?.tintColor = color
    }

    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}

Call these extension method like this:像这样调用这些扩展方法:

searchBarTextField.setMagnifyingGlassColorTo(color: yourColor)
searchBarTextField.setClearButtonColorTo(color: yourColor)
searchBarTextField.setPlaceholderTextColorTo(color: yourColor)

As per Federica's anwser....To do this in swift根据 Federica's anwser .... 迅速做到这一点

var image: UIImage = UIImage(named: "search")!
self.searchBar.setImage(image, forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)

For just changing the color of the search icon, without altering the actual icon in Swift 3:仅更改搜索图标的颜色,而不更改 Swift 3 中的实际图标:

if let textField = self.searchBar.value(forKey: "searchField") as? UITextField,
    let iconView = textField.leftView as? UIImageView {

    iconView.image = iconView.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
    iconView.tintColor = UIColor.red
}

Creates a result like so:创建如下结果:

改变的搜索栏图标

A solution for those using interface builder.适用于使用界面构建器的人的解决方案。 You can add a User Defined Runtime Attribute to the UISearchBar:您可以向 UISearchBar 添加用户定义的运行时属性:

searchField.leftView.tintColor of type Color You can select the desired color of the icon, can be selected from your Color Assets library to support different colors for both light and dark mode. Color类型的searchField.leftView.tintColor您可以选择所需的图标颜色,可以从您的颜色资产库中选择以支持浅色和深色模式的不同颜色。

在此处输入图片说明

Following on from some of the answers here继这里的一些答案之后

If you would like to see and make the changes in storyboard first subclass UISearch bar and do as above.如果您想在故事板第一个子类 UISearch 栏中查看并进行更改,请执行上述操作。

However add the changes in a @IBInspectable variable and not forgetting the @IBDesignable at the top of the class and setting the searchbar subclass in the "Identity inspector"但是,在@IBInspectable 变量中添加更改,不要忘记类顶部的@IBDesignable 并在“身份检查器”中设置搜索栏子类

I have added the full working subclass and code below for swift 3.0 Here you will be able to change the placeholder text, search text and magnifying glass我在下面为 swift 3.0 添加了完整的工作子类和代码 在这里您将能够更改占位符文本、搜索文本和放大镜

import UIKit

@IBDesignable

class CustomSearchBar: UISearchBar {
@IBInspectable var placeholderColor: UIColor? {
    didSet {

        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = placeholderColor
    }
}

@IBInspectable var textColor: UIColor? {
    didSet {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = textColor
    }
}

@IBInspectable var magnifyingGlassColor: UIColor? {

    didSet {

        if let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField,
            let glassIconView = textFieldInsideSearchBar.leftView as? UIImageView {

            //Magnifying glass
            glassIconView.image = glassIconView.image?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
            glassIconView.tintColor = magnifyingGlassColor

        }        }
}

} }

Make sure that when you use the setImage API, pass an image with rendering mode of UIImageRenderingModeAlwaysTemplate .确保在使用setImage API 时,传递渲染模式为UIImageRenderingModeAlwaysTemplate的图像。 For example:例如:

[self.searchBar setImage:[[UIImage imageNamed: @"icon-search"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

There are no adequate reasons to set your own custom image just for changing icon tint color.没有足够的理由来设置您自己的自定义图像只是为了更改图标色调颜色。 Don't forget about perfomance.不要忘记性能。 And retrieving a value by a raw string key doesn't garantee that other coders can mistype usually calling app crashes .并且通过原始字符串键检索值并不能保证其他编码人员通常会错误输入 app crashes We're not perfect.我们并不完美。

How about UISearchBar instance's property searchTextField ( UISearchTextField )? UISearchBar实例的属性searchTextField ( UISearchTextField ) 怎么样?

if let thatMysteriousLoop = yourSearchBar.searchTextField.leftView as? UIImageView {
    thatMysteriousLoop.tintColor = anyColorYouWannaSet // <-- Voilà!
}

快速 3

        searchBar.setImage(UIImage(named: "location-icon-black"), for: .search, state: .normal)

Since iOS 13, we now have access to many standard system icons via SF Symbols.从 iOS 13 开始,我们现在可以通过 SF Symbols 访问许多标准系统图标。 Also, if you want to have a unified colour scheme for your search bars so that they all look the same without having to duplicate code, you can use the Appearance workflow to change them all at once.此外,如果您想为搜索栏采用统一的配色方案,以便它们看起来都一样而无需重复代码,您可以使用Appearance工作流程一次性更改它们。 For example:例如:

    let image = UIImage(systemName: "magnifyingglass")?.withTintColor(.white, renderingMode: .alwaysOriginal)
    UISearchBar.appearance().setImage(image, for: .search, state: .normal)

This code sets all search bars in the app to use the standard magnifying glass icon, in white.此代码将应用程序中的所有搜索栏设置为使用标准的白色放大镜图标。 You can use similar code to change the 'clear' button icon, the bookmark icon and the results list icon.您可以使用类似的代码来更改“清除”按钮图标、书签图标和结果列表图标。 You just need to change .search to the appropriate enumeration value and find the system name of the appropriate icon (which you can get from the free SF System app).您只需将.search更改为适当的枚举值并找到适当图标的系统名称(您可以从免费的 SF System 应用程序中获取)。

Another method that uses Appearance would be to set the tint colour of all views contained within a search view, though this may have unwanted effects in some cases (ie changing the colour of the text cursor):另一种使用Appearance方法是设置搜索视图中包含的所有视图的色调颜色,尽管这在某些情况下可能会产生不需要的效果(即更改文本光标的颜色):

UIView.appearance(whenContainedInInstancesOf: [UISearchBar.self]).tintColor = .yellow

This will make the left icon and the text cursor yellow, though annoyingly not the 'clear' button for some reason.这将使左侧图标和文本光标变黄,但由于某种原因令人讨厌地不是“清除”按钮。 I prefer not to use this method as it may not be future-proof;我不喜欢使用这种方法,因为它可能不是面向未来的; Apple has a habit of changing things internally that can cause unexpected changes if you don't use their approved methods. Apple 习惯于在内部进行更改,如果您不使用他们批准的方法,可能会导致意外更改。

I know it is an old post but since there is a Xamarin Bug on the dark mode and I was struggling for hours, I thought I share my pretty easy solution.我知道这是一篇旧帖子,但由于在黑暗模式下有一个 Xamarin 错误并且我挣扎了几个小时,我想我想分享我的非常简单的解决方案。

iOS- custom Renderer. iOS-自定义渲染器。

[assembly:ExportRenderer(typeof(SearchBar),typeof(YourProjectSearchbarRenderer))] [程序集:ExportRenderer(typeof(SearchBar),typeof(YourProjectSearchbarRenderer))]

public class YourProjectSearchbarRenderer : SearchBarRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);

        if (e.NewElement != null)
        {
            // iOS >13 -> Xamarin bug on darkmode,
            // just shows the light icon...
            this.Control.SetImageforSearchBarIcon(UIImage.FromFile("AddAnSearchIcon.ico"), UISearchBarIcon.Search, UIControlState.Normal); 
        }
    }
}

My solution:我的解决方案:

searchBar = UISearchBar()
searchBar.searchBarStyle = .minimal
searchBar.setTextColor(.white)
let textField = self.searchBar.getTextField()
let glassIconView = textField?.leftView as? UIImageView
glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
glassIconView?.tintColor = .white
searchBar.showsCancelButton = true

extension UISearchBar {
    func getTextField() -> UITextField? {
        return self.value(forKey: "searchField") as? UITextField
    }

    func setTextColor(_ color: UIColor) {
        let textField = getTextField()
        textField?.textColor = color
    }
}
if(IOS_7) {
    self.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    self.searchBar.backgroundImage = [UIImage imageWithColor:[UIColor redColor] cornerRadius:5.0f];
}

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

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