ios 如何更改 UISearchBar 搜索文本颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28499701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:49:35  来源:igfitidea点击:

How can I change the UISearchBar search text color?

iosswiftuisearchbar

提问by MrTourkos

How can I change the text color of a UISearchBar?

如何更改 a 的文本颜色UISearchBar

回答by Christian

You have to access the UITextFieldinside the UISearchBar. You can do that by using valueForKey("searchField")

您必须访问UITextFieldUISearchBar 内部。你可以通过使用做到这一点valueForKey("searchField")

var textFieldInsideSearchBar = yourSearchbar.valueForKey("searchField") as? UITextField

textFieldInsideSearchBar?.textColor = yourcolor

Swift 3 update

斯威夫特 3 更新

let textFieldInsideSearchBar = yourSearchbar.value(forKey: "searchField") as? UITextField

textFieldInsideSearchBar?.textColor = yourcolor

回答by interrupt

If you want to set text color for UISearchBar in storyboard (without code), it is easy to do as well (in identity inspector). Here is a red text for search bar.

如果您想在故事板中为 UISearchBar 设置文本颜色(无需代码),也很容易(在身份检查器中)。这是搜索栏的红色文本。

enter image description here

在此处输入图片说明

回答by chronikum

Working in Swift 4 for me:

为我在 Swift 4 中工作:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]

Swift 4.2, IOS 12:

斯威夫特 4.2,IOS 12:

UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]

回答by Bacon

If you only need to make it readable on a dark background you can change the barStyle. The following makes text and buttons in the searchbar white:

如果您只需要使其在深色背景上可读,您可以更改 barStyle。以下使搜索栏中的文本和按钮变为白色:

searchController.searchBar.barStyle = .black

回答by Adam Waite

public extension UISearchBar {

    public func setTextColor(color: UIColor) {
        let svs = subviews.flatMap { 
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.blue
.subviews } guard let tf = (svs.filter {
    extension UISearchBar {

       var textColor:UIColor? {
           get {
               if let textField = self.value(forKey: "searchField") as? 
   UITextField  {
                   return textField.textColor
               } else {
                   return nil
               }
           }

           set (newValue) {
               if let textField = self.value(forKey: "searchField") as? 
   UITextField  {
                   textField.textColor = newValue
               }
           }
       }
   }
is UITextField }).first as? UITextField else { return } tf.textColor = color } }

回答by juanjo

This works for me on iOS 11, Xcode 9:

这在 iOS 11、Xcode 9 上对我有用:

searchBar.textColor = UIColor.blue // Your color

I write it in the AppDelegatebut I guess it works if you put it somewhere else too.

我把它写在了,AppDelegate但我想如果你把它放在别的地方也行。

回答by Tal Zion

The most convenient way I think is to set a textColorproperty in UISearchBar.

我认为最方便的方法是textColorUISearchBar.

Swift 3.0

斯威夫特 3.0

extension UISearchBar {

 var textColor:UIColor? {
     get {
         if let textField = self.valueForKey("searchField") as? UITextField  {
             return textField.textColor
         } else {
             return nil
         }
     }

     set (newValue) {
         if let textField = self.valueForKey("searchField") as? UITextField  {
             textField.textColor = newValue
         }
     }
 }
} 

Usage

用法

searchBar.textColor = UIColor.blueColor() // Your color

Swift 2.3

斯威夫特 2.3

searchBar.searchTextField

You would use it as:

您可以将其用作:

extension UISearchBar {
    public var textField: UITextField? {
        if #available(iOS 13.0, *) {
            return searchTextField
        } 

        guard let firstSubview = subviews.first else {
            assertionFailure("Could not find text field")
            return nil
        }

        for view in firstSubview.subviews {
            if let textView = view as? UITextField {
                return textView
            }
        }

        assertionFailure("Could not find text field")

        return nil
    }
}

回答by Saren Inden

Since Xcode 11 and iOS 13 it has become possible to access the text field directly:

从 Xcode 11 和 iOS 13 开始,可以直接访问文本字段:

extension UISearchBar {
    public var textField: UITextField {
        if #available(iOS 13.0, *) {
            return searchTextField
        }

        guard let firstSubview = subviews.first else {
            fatalError("Could not find text field")
        }

        for view in firstSubview.subviews {
            if let textView = view as? UITextField {
                return textView
            }
        }

       fatalError("Could not find text field")
    }
}

You could write some code to always make it accessible like this.

您可以编写一些代码以使其始终可以像这样访问。

    var textField: UITextField? {
        if #available(iOS 13.0, *) {
            return self.searchTextField
        }
        return subviews.first?.subviews.first(where: { 

class SearchBar: UISearchBar, UISearchBarDelegate {

    var textField: UITextField? {
        if #available(iOS 13.0, *) {
            return self.searchTextField
        }
        return subviews.first?.subviews.first(where: { 
        let searchBar = UISearchBar.appearance(whenContainedInInstancesOf: [SearchBar.self])
        searchBar.backgroundImage = UIImage()
        searchBar.isTranslucent = false
        searchBar.returnKeyType = .search
as? UITextField != nil }) as? UITextField } override func awakeFromNib() { super.awakeFromNib() delegate = self if let textField = textField { textField.textColor = .red textField.clearButtonMode = .whileEditing textField.returnKeyType = .search } } }
as? UITextField != nil }) as? UITextField }

You could also make it not optional with fatal errors, this code is tested since iOS 7 up to iOS 13GM. But i would just go for the optional version.

您也可以使用致命错误使其不可选,此代码从 iOS 7 到 iOS 13GM 进行了测试。但我只会选择可选版本。

extension UISearchBar {
    /// Return text field inside a search bar
    var textField: UITextField? {
        let subViews = subviews.flatMap { ##代码##.subviews }
        guard let textField = (subViews.filter { ##代码## is UITextField }).first as? UITextField else { return nil
        }
        return textField
    }
}

回答by Bryan ORTIZ

I tried a few of the solutions written above but they didn't work (anymore, I guess).

我尝试了上面写的一些解决方案,但它们没有用(我猜是了)。

If you only want to handle iOS 13:

如果您只想处理 iOS 13:

mySearchBar.searchTextField.textColor = .red

mySearchBar.searchTextField.textColor = .red

But if you want to handle older iOS too, Here is the way I did :

但是,如果您也想处理较旧的 iOS,我是这样做的:

Create a custom UISearchBarclass, called SearchBar : UISearchBar, UISearchBarDelegateThis SearchBarwill have the UISearchBarDelegatemethods I wanna handle and its delegateset.

创建一个UISearchBar名为SearchBar : UISearchBar, UISearchBarDelegateThis的自定义类,SearchBar它将包含UISearchBarDelegate我想要处理的方法及其delegate集合。

And I add to the class:

我添加到课堂上:

##代码##

Short explanation:

简短说明:

With iOS13 now, you can access the UITextFieldthanks to UISearchBar.searchTextField, which is of type UISearchTextField, which inherits from UITextField.

现在使用 iOS13,您可以访问UITextField感谢UISearchBar.searchTextField,其类型为UISearchTextField,继承自UITextField.

Since I know my hierarchy, I know my textFieldwon't be nillfor older versions so in both case, I get a textfield I can easily customize, working on every version, from 9 to 13 today.

因为我知道我的层次结构,我知道我textField不会nill用于旧版本,所以在这两种情况下,我都会得到一个文本字段,我可以轻松自定义,处理每个版本,从今天的 9 到 13。

Here is the full code needed to make it work:

这是使其工作所需的完整代码:

##代码##

You can also set some customization on SearchBarby adding this on the :

您还可以SearchBar通过在以下内容上添加以下内容来设置一些自定义:

##代码##

Then you set it to the XIB / Storyboard and you handle it like if it were a simple UISearchBar(if you did not forget the delegates !).

然后你将它设置为 XIB/Storyboard 并像处理简单一样处理它UISearchBar(如果你没有忘记代表!)。

回答by Omar Albeik

You can do this by accessing the UITextField inside the searchBar, then you can change its background color, text color, and all other UITextField properties

您可以通过访问 searchBar 内的 UITextField 来完成此操作,然后您可以更改其背景颜色、文本颜色和所有其他 UITextField 属性

add the following extension to access the textField

添加以下扩展名以访问 textField

##代码##