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

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

本文介绍了如何在UISearchController中更改文本字段的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to change the default grey background at UISearchController search text field?

推荐答案

以下是有关如何设置 textField 背景的示例.

Here is a an example on how to set the textField background.

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中更改文本字段的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 16:07