如何更改 UISearchController 中文本字段的背景颜色?

How to change background color of the text field in the UISearchController?

如何更改 UISearchController 搜索文本字段的默认灰色背景?

你有没有试过

searchController.searchBar.backgroundColor = UIColor.blue

这里有一个关于如何设置 textField 背景的例子。

class ViewController: UIViewController {

    let searchController = UISearchController(searchResultsController: nil)

    private lazy var searchTextField: UITextField? = { [unowned self] in
        var textField: UITextField?
        self.searchController.searchBar.subviews.forEach({ view in
            view.subviews.forEach({ view in
                if let view  = view as? UITextField {
                    textField = view
                }
            })
        })
        return textField
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search Candies"
        navigationItem.searchController = searchController
        definesPresentationContext = true

        if let bg = self.searchTextField?.subviews.first {
            bg.backgroundColor = .green
            bg.layer.cornerRadius = 10
            bg.clipsToBounds = true
        }
    }
}

结果

要更新 UISearchController 的背景,正确的方法是更改​​背景图像。

如果您在可视化调试器中看到 UISearchController,您会发现它的背景是 UIImageView:

所以你应该制作你的搜索栏的小图像并将其设置为 seachBar,如下所示:

    lazy var searchController: UISearchController = {

        let searchController = UISearchController(searchResultsController: nil)

        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.tintColor = UIColor.black
        searchController.searchBar.searchBarStyle = .minimal
        // Set background image to searchBar so it will resize
        searchController.searchBar.setSearchFieldBackgroundImage(UIImage(named: "oval_static"), for: .normal)

        definesPresentationContext = true

        return searchController
    }()

searchBar图片(项目中推荐使用.pdf或.png格式的图片,这里只是截图):

UISearchBar 会根据需要调整它的大小,结果是:

此外,我们可以像这样在代码中创建自定义背景:

/// Just random extension to make image from UIView, you can use your own
extension UIView {

func asImage() -> UIImage {
    let renderer = UIGraphicsImageRenderer(bounds: bounds)
    return renderer.image { rendererContext in
        layer.render(in: rendererContext.cgContext)
    }
}}

lazy var searchController: UISearchController = {

        let searchController = UISearchController(searchResultsController: nil)

        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.tintColor = UIColor.black
        searchController.searchBar.searchBarStyle = .minimal

        // Create own view with custom properties
        // Default height is 36 points
        let differentColorSearchBar = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 36))

        differentColorSearchBar.layer.cornerRadius = 8
        differentColorSearchBar.clipsToBounds = true
        differentColorSearchBar.backgroundColor = UIColor.blue

        searchController.searchBar.setSearchFieldBackgroundImage(differentColorSearchBar.asImage(), for: .normal)

        definesPresentationContext = true

        return searchController
    }

结果是(当然你可以更改 searchBar 的其他属性以使其更好,但我只是告诉你如何正确更改背景):

我建议避免私有属性,只使用 open!希望能有所帮助。

我是这样做的,Objective-C代码:

UITextField *searchField = [_navigationSearchBar valueForKey:@"searchField"];
searchField.backgroundColor = [UIColor defaultSeacrhBarColor];
searchField.textColor = [UIColor defaultWhiteColor];
searchField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchTitle];
UILabel *placeholderLabel = [searchField valueForKey:@"placeholderLabel"];
placeholderLabel.textColor = [UIColor lightTextColor];

UIButton *clearButton = [searchField valueForKey:@"clearButton"];
[clearButton setImage:[clearButton.imageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
clearButton.tintColor = [UIColor defaultWhiteColor];

_navigationSearchBar.delegate = self;
[_navigationSearchBar setTranslucent:NO];
[_navigationSearchBar setBackgroundImage:nil];
[_navigationSearchBar setBarTintColor:[UIColor defaultNavigationBarColor]];
[_navigationSearchBar setBackgroundColor:[UIColor defaultNavigationBarColor]];
[_navigationSearchBar setImage:[UIImage imageNamed:@"Search_Icon"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
_navigationSearchBar.clipsToBounds = YES;
[_navigationBar addSubview:_navigationSearchBar];

Apple 有密钥 'searchField' 来检测搜索栏中的文本字段。因此,首先安全地获取该文本字段并使用文本字段进行任何更改。

let searchController = UISearchController(searchResultsController: nil)
searchController.searchResultsUpdater = self
searchController.searchBar.placeholder = "Search here..."
searchController.searchBar.delegate = self
searchController.searchBar.tintColor = .white
searchController.searchBar.barTintColor = .white
searchController.hidesNavigationBarDuringPresentation = false
searchController.obscuresBackgroundDuringPresentation = false

if let textfield = searchController.searchBar.value(forKey: "searchField") as? UITextField {

    // Set text colour of text field   
    textfield.textColor = UIColor.blue

    if let backgroundview = textfield.subviews.first {

        // Get background view and change background color
        backgroundview.backgroundColor = UIColor.white

        // Set rounded corner
        backgroundview.layer.cornerRadius = 10
        backgroundview.clipsToBounds = true
    }
}

if #available(iOS 11.0, *) {
    self.navigationItem.searchController = searchController
} else {
    self.tblCustomers.tableHeaderView = searchController.searchBar
}

这是工作代码,我已经在我当前的项目中实现了。不过,如果您有任何疑问,请告诉我。

希望对您有所帮助。

最大使用下面这个函数来改变颜色。

extension UISearchBar {
  func setBackgroundColor(){
    if let view:UIView = self.subviews.first {
        for curr in view.subviews {
            guard let searchBarBackgroundClass = NSClassFromString("UISearchBarBackground") else {
                return
            }
            if curr.isKind(of:searchBarBackgroundClass){
                if let imageView = curr as? UIImageView{
                    imageView.backgroundColor = .red
                    break
                }
            }
        }
    }
  }
}

将此功能与 searchbar 一起使用。

searchBarController.searchBar.setBackgroundColor()

没有任何 proper/public 方法可以更改此搜索栏的背景颜色。有一些使用私有 api 的方法,比如@sanjayshah 的回答,但在那种情况下,苹果可能会拒绝您的申请。我认为您应该继续使用默认背景颜色。大多数应用程序使用相同的。

@Kamran 答案的递归版本,具有更好的最佳情况和平均 运行 时间。接受的版本对我来说不适用于 iOS 13+。

private lazy var searchTextField: UITextField? = { [unowned self] in
    guard let searchBar = self.searchController?.searchBar else { return nil }
    var views =  searchBar.subviews
    while !views.isEmpty {
        guard let view = views.popLast() else { break }
        if let textfield = view as? UITextField {
            return textfield
        }
        views += view.subviews
    }
    return nil
}()

在 iOS13 及以后,searchTextField 是 UISearchBar 的成员。所以你可以使用这样的东西:

searchController.searchBar.searchTextField.backgroundColor = UIColor.blue

注意,苹果在 SDK 中没有正确的符号显示 iOS 13 中引入了这个 属性,所以如果你支持 iOS 12 或更早版本,它不会显示你有什么警告。确保只为 iOS 13 包装它。

首先检查平台,

不如做修改,因为IOS13不接受很多花样为IOS12

做的
if #available(iOS 13, *) {
   searchController.searchBar.searchTextField.backgroundColor = .white 
} else {

for textField in searchController.searchBar.subviews.first.subviews where   textField is UITextField {
textField.subviews.first.backgroundColor = .white
textField.subviews.first.layer.cornerRadius = 10
textField.subviews.first.layer.masksToBounds = true
  }
}

在iOS12及以下需要覆盖textfield内部的图片,该图片给出了我们想要改变的背景颜色。 您可以在图像视图之后的索引 1 处添加自定义视图,以实现您想要的效果。

if #available(iOS 13.0, *)
    {
        searchBar.searchTextField.textColor       = .black
        searchBar.searchTextField.backgroundColor = .red
    }
    else if let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
    {
        textFieldInsideSearchBar.textColor = .black
        let backgroundView = UIView(frame: textFieldInsideSearchBar.bounds)
        backgroundView.backgroundColor = .red
        backgroundView.layer.cornerRadius = 10
        backgroundView.clipsToBounds = true
        textFieldInsideSearchBar.insertSubview(backgroundView, at: 1)
    }