Search code examples
iosswiftios11uisearchcontroller

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


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

Screen shot


Solution

  • 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
            }
        }
    }
    

    Result

    enter image description here