How to clear UISearchBar background color in iOS10 Swift?

10,154

Solution 1

private func clearBackgroundColor() {
    guard let UISearchBarBackground: AnyClass = NSClassFromString("UISearchBarBackground") else { return }

    for view in self.subviews {
        for subview in view.subviews where subview.isKind(of: UISearchBarBackground) {
            subview.alpha = 0
        }
    }
}

This is what I did in the end that worked. Thanks all for your answers.

Solution 2

I think you are mention about BarTintColor of search bar

try this:

searchBar.barTintColor = .white

Solution 3

Try this.

class CustomSearchBar: UISearchBar {
    override func layoutSubviews() {
        super.layoutSubviews()
        clearBackgroundColor() // function in the question
    }
}

private func clearBackgroundColor() {
    for view in self.subviews {
        view.backgroundColor = UIColor.clear
        for subview in view.subviews {
            subview.backgroundColor = UIColor.clear
        }
    }
} 

Solution 4

try set backgroundimage: [searchBar setBackgroundImage:[UIImage new]];

Solution 5

Just set the Search Bar style to .Minimal in Interface Builder or code and the background will go transparent.

enter image description here

Share:
10,154
RainCast
Author by

RainCast

Hey! check out my app from app store:

Updated on June 25, 2022

Comments

  • RainCast
    RainCast almost 2 years

    There are older version of this question for older versions of iOS no longer works due to the layout changes in UISearchBar.

    I've tried the following to completely remove the background color of UISearchBar but it doesn't work. (I tried to look up the hierarchy views of it but xCode kept crashing for this option.)

    private func clearBackgroundColor() {
        for view in self.subviews {
            view.backgroundColor = UIColor.clear
            for subview in view.subviews {
                subview.backgroundColor = UIColor.clear
            }
        }
    } 
    

    Any ideas or suggestions?

    Thanks!!