ios 无法更改搜索栏背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33751292/
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 08:15:24  来源:igfitidea点击:

Cannot change search bar background color

iosswiftuisearchbar

提问by Orkhan Alizade

I have a search bar:

我有一个搜索栏:

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))

and I want to change text input part background color. For this I've tried:

我想更改文本输入部分的背景颜色。为此,我尝试过:

searchBar.barTintColor = UIColor(red: 0/255, green: 74/255, blue: 103/255, alpha: 1)

searchBar.backgroundColor = UIColor.redColor()

but these both variants do not work. How can I change background color of my UISearchBar textInput part and what I did wrong?

但是这两种变体都不起作用。如何更改 UISearchBar textInput 部分的背景颜色以及我做错了什么?

回答by ángel Téllez

Like @aliamcami, all the answers before did not work as I would expect, either the answer did not work for me or it works but it needs too much "dummy" code. So I share another answer wrote in Swift 4with simplified logic:

像@aliamcami 一样,之前的所有答案都没有像我预期的那样有效,要么答案对我不起作用,要么有效,但它需要太多“虚拟”代码。所以我分享了另一个在Swift 4中用简化逻辑编写的答案:

for textField in searchController.searchBar.subviews.first!.subviews where textField is UITextField {
    textField.subviews.first?.backgroundColor = .white
    textField.subviews.first?.layer.cornerRadius = 10.5 //I set 10.5 because is approximately the system value
    textField.subviews.first?.layer.masksToBounds = true
    //Continue changing more properties...
}

textField.subviews.firstis the "_UISearchBarSearchFieldBackgroundView" subview which add visual effects behind the UIFieldEditor.

textField.subviews.first是“_UISearchBarSearchFieldBackgroundView”子视图,它在UIFieldEditor.



Edited

已编辑

After some development and many bugs, I finished with this elegantsolution (that I am sure Apple would not be happy to approve, but I do not know) that works from iOS 10to iOS 12:

经过一些开发和许多错误之后,我完成了这个从iOS 10iOS 12 都有效的优雅解决方案(我相信 Apple 不会乐意批准,但我不知道):

if let textField = searchBar.value(forKey: "searchField") as? UITextField {
    textField.backgroundColor = myColor
    //textField.font = myFont
    //textField.textColor = myTextColor
    //textField.tintColor = myTintColor
    // And so on...

    let backgroundView = textField.subviews.first
    if #available(iOS 11.0, *) { // If `searchController` is in `navigationItem`
        backgroundView?.backgroundColor = UIColor.white.withAlphaComponent(0.3) //Or any transparent color that matches with the `navigationBar color`
        backgroundView?.subviews.forEach({ 
for view in searchBar.subviews {
            for subview in view.subviews {
                if subview .isKindOfClass(UITextField) {
                    let textField: UITextField = subview as! UITextField
                    textField.backgroundColor = UIColor.redColor()
                }
            }
        }
.removeFromSuperview() }) // Fixes an UI bug when searchBar appears or hides when scrolling } backgroundView?.layer.cornerRadius = 10.5 backgroundView?.layer.masksToBounds = true //Continue changing more properties... }

When the searchBaris in the tableHeaderViewthe above code can be called in viewWillAppear, but if it is in the navigationItemon iOS 11 and above it should be called in viewDidAppear.

当上面代码中的searchBaris 时tableHeaderView可以调用 in viewWillAppear,但如果是在navigationItemiOS 11 及以上版本中则应该调用 in viewDidAppear

回答by Imran

If you only want to change it in your ViewController and don't want anywhere else to effect then use

如果您只想在 ViewController 中更改它并且不想在其他任何地方生效,请使用

UITextField.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).backgroundColor = UIColor.redColor()

But if you want it to be change in whole app and targeting the iOS 9.0 or later then should be using appearanceWhenContainedInInstancesOfClasses like

但是,如果您希望它在整个应用程序中进行更改并针对 iOS 9.0 或更高版本,则应该使用 AppearanceWhenContainedInInstancesOfClasses,例如

for subView in searchBar.subviews
{
    for subView1 in subView.subviews
    {

        if subView1.isKindOfClass(UITextField)
        {
            subView1.backgroundColor = UIColor.redColor()
        }
    }

}

回答by Kirit Modi

You are adding the below code in ViewDidLoad and Change the textfield background color RED,

您在 ViewDidLoad 中添加以下代码并将文本字段背景颜色更改为红色,

for subView in searchController.searchBar.subviews {

    for subViewOne in subView.subviews {

        if let textField = subViewOne as? UITextField {

           subViewOne.backgroundColor = UIColor.red

           //use the code below if you want to change the color of placeholder
           let textFieldInsideUISearchBarLabel = textField.value(forKey: "placeholderLabel") as? UILabel
                textFieldInsideUISearchBarLabel?.textColor = UIColor.blue
        }
     }
}

Red Color of TextField in SearchBar.

SearchBar 中 TextField 的红色。

enter image description here

在此处输入图片说明

回答by Alien

For Swift 3+, use this:

对于 Swift 3+,使用这个:

self.searchBar.setSearchFieldBackgroundImage(UIImage(named: "SearchFieldBackground"), for: UIControlState.normal)

回答by SuperDuperTango

The way to do this only using Apple APIs is to create an image and use setSearchFieldBackgroundImage:

仅使用 Apple API 执行此操作的方法是创建图像并使用setSearchFieldBackgroundImage

import UIKit

extension UISearchBar {

    // Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
    var compatibleSearchTextField: UITextField {
        guard #available(iOS 13.0, *) else { return legacySearchField }
        return self.searchTextField
    }

    private var legacySearchField: UITextField {
        if let textField = self.subviews.first?.subviews.last as? UITextField {
            // Xcode 11 previous environment
            return textField
        } else if let textField = self.value(forKey: "searchField") as? UITextField {
            // Xcode 11 run in iOS 13 previous devices
            return textField
        } else {
            // exception condition or error handler in here
            return UITextField()
        }
    }
}

It will even animate the corners properly if you create a rounded rect and dynamically show and hide buttons.

如果您创建圆角矩形并动态显示和隐藏按钮,它甚至可以正确地为角设置动画。

Example using this image: enter image description here

使用此图像的示例: 在此处输入图片说明

enter image description here

在此处输入图片说明

回答by Joshpy

I did one UISearchBar extension & category for customize text filed within search bar.

我做了一个 UISearchBar 扩展和类别来自定义搜索栏中的文本。

Compatible from iOS 9 to iOS 13.

兼容从 iOS 9 到 iOS 13。

Swift 4+

斯威夫特 4+

var searchController: UISearchController?
searchController?.searchBar.compatibleSearchTextField.textColor = UIColor.XXX
searchController?.searchBar.compatibleSearchTextField.backgroundColor = UIColor.XXX

Usage Example:

用法示例:

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UISearchBar (SearchTextField)

// Due to searchTextField property who available iOS 13 only, extend this property for iOS 13 previous version compatibility
@property (nonatomic, readonly) UITextField *compatibleSearchTextField;

@end

NS_ASSUME_NONNULL_END


Objective-C

目标-C

UISearchBar+SearchTextField.h

UISearchBar+SearchTextField.h

#import "UISearchBar+SearchTextField.h"

@implementation UISearchBar (SearchTextField)

- (UITextField *)compatibleSearchTextField {
    if (@available(iOS 13.0, *)) {
#ifdef __IPHONE_13_0
        return self.searchTextField;
#else
        // Xcode 11 run in iOS 13 previous devices
        return (UITextField *)[self valueForKey:@"searchField"];
#endif
    } else {
        // Xcode 11 previous environment
        return [[[self.subviews firstObject] subviews] lastObject];
    }
}

@end

UISearchBar+SearchTextField.m

UISearchBar+SearchTextField.m

- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(X, X, X, X)];
        _searchBar.compatibleSearchTextField.textColor = [UIColor XXX];
        _searchBar.compatibleSearchTextField.backgroundColor = [UIColor XXX];
    }
    return _searchBar
}

Usage Example:

用法示例:

let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
textFieldInsideSearchBar?.backgroundColor = UIColor.red


回答by Nosov Pavel

I do it with this way(Swift 3+ solution):

我用这种方式(Swift 3+ 解决方案):

let searchBar:UISearchBar = UISearchBar(frame: CGRectMake((searchView.frame.width - UIScreen.mainScreen().bounds.width / 1.6) / 2, 0, UIScreen.mainScreen().bounds.width / 1.6, 24))
let searchTextField = searchBar.valueForKey("_searchField") as? UITextField
searchTextField?.backgroundColor = UIColor.redColor()

回答by Kingiol

Just like this

像这样

    searchController.searchBar.searchTextField.backgroundColor = .white

回答by Joshua Hart

Swift 5:

斯威夫特 5:

 let searchController = UISearchController(searchResultsController: nil)
 navigationItem.searchController = searchController

 searchController.searchBar.barTintColor = viewBackgroundColor
 searchController.searchBar.backgroundColor = viewBackgroundColor

 searchController.searchBar.searchTextField.borderStyle = .none
 searchController.searchBar.searchTextField.backgroundColor = .white
 searchController.searchBar.searchTextField.layer.cornerRadius = 10
 searchController.searchBar.searchTextField.clipsToBounds = true

回答by Sudarshan Sreeram

I was experimenting with the properties of searchBar and searchTextField when I found a solution to the above.

当我找到上述问题的解决方案时,我正在试验 searchBar 和 searchTextField 的属性。

Below, I have listed the steps in order to achieve the desired result:

下面,我列出了实现预期结果的步骤:

  1. Set the border style of the searchTextField to .none
  2. Set the background color of the searchTextField to your desired color
  3. Change the corner radius of the searchTextField's layer to 10
  4. Set the searchTextField's clipToBounds property to true
  1. 将searchTextField的边框样式设置为.none
  2. 将 searchTextField 的背景颜色设置为您想要的颜色
  3. 将searchTextField的图层的角半径更改为10
  4. 将 searchTextField 的 clipToBounds 属性设置为 true

Further, I have provided the code below for your reference:

此外,我提供了以下代码供您参考:

##代码##

Note: searchTextField is in Beta and available on iOS 13

注意:searchTextField 处于 Beta 版,可在 iOS 13 上使用