Amey
Amey

Reputation: 815

how to change uitextfield color in searchcontroller?

enter image description here

i have embedded SearchController in navigation bar . How to Change UITextField Color The one which Holds search String To White .?

Upvotes: 3

Views: 1380

Answers (2)

Ashutosh Mane
Ashutosh Mane

Reputation: 11

Excellent answer, in my novice opinion we could also try using the member of the UI Search bar called searchTextField which is ultimately a subclass of UITextField but we can get away without using

if let textfield = scb.value(forKey: "searchField") as? UITextField
//we could use 
let textField = scb.searchTextField
followed by the same changes made to the views layer, cornerRadius etc

Upvotes: 0

Krunal
Krunal

Reputation: 79776

This will help you to achieve, what you want. Just apply your color combination in this code and see.

if #available(iOS 11.0, *) {
            let sc = UISearchController(searchResultsController: nil)
            sc.delegate = self
            let scb = sc.searchBar
            scb.tintColor = UIColor.white
            scb.barTintColor = UIColor.white


            if let textfield = scb.value(forKey: "searchField") as? UITextField {
                //textfield.textColor = // Set text color
                if let backgroundview = textfield.subviews.first {

                    // Background color
                    backgroundview.backgroundColor = UIColor.white

                    // Rounded corner
                    backgroundview.layer.cornerRadius = 10;
                    backgroundview.clipsToBounds = true;

                }
            }

            if let navigationbar = self.navigationController?.navigationBar {
                navigationbar.barTintColor = UIColor.blue
            }
            navigationItem.searchController = sc
            navigationItem.hidesSearchBarWhenScrolling = false

}

Result:

enter image description here

Upvotes: 5

Related Questions