I am not able to clear search bar I have tried to make it clear by setting its background color clear and I have also placed one image under searchbar
I have also ma
I tried @Johnson's answer however it didn't work well for me. (iOS 13, swift 5)
However the logic behind the solution seemed well. So tried to iterate all subviews of the searchBar and it worked!
I hope, it will help :)
Solution also worked for me in iOS 12.4 - swift 5
Remove Background Method
private func removeBackground(from searchBar: UISearchBar) {
guard let BackgroundType = NSClassFromString("_UISearchBarSearchFieldBackgroundView") else { return }
for v in searchBar.allSubViewsOf(type: UIView.self) where v.isKind(of: BackgroundType){
v.removeFromSuperview()
}
}
Helper Methods -> UIViewExtension
extension UIView {
public func allSubViewsOf<T : UIView>(type : T.Type) -> [T]{
var all = [T]()
func getSubview(view: UIView) {
if let wrapped = view as? T, wrapped != self{
all.append(wrapped)
}
guard view.subviews.count>0 else { return }
view.subviews.forEach{ getSubview(view: $0) }
}
getSubview(view: self)
return all
}
}
For anyone trying to find a non hacky solution to this, just set the background image to nil on your Storyboard/Xib file. Literally, simply write nil
in the background image field of the UISearchBar.
For iOS 13+ we can simply use:
searchBar.searchTextField.backgroundColor = .clear
but other solutions like:
searchBar.setSearchFieldBackgroundImage(UIImage(), for: .normal)
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
creates a background on the searchBar which hides the placeholder and doesn't allow to interact with the searchBar. The solution for iOS 12 and below is to use an approach similar to @Get Schwifty.
searchBarStyle = .default
searchTextField.backgroundColor = .yourColor
With this combination, you can remove the gray background of searchTextField and set yours!
For iOS7+, all you need to do is:
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBarTintColor:[UIColor clearColor]]; //this is what you want
NOTE: This will not work for iOS6
For iOS6+, the following will take care of it even in iOS7:
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];
[self.searchBarHome setBackgroundImage:[UIImage new]];
[self.searchBarHome setTranslucent:YES];
Here's my solution in Swift 3 (a combo of Scarafone's and Andrew2M's answers):
for view in searchBar.subviews.last!.subviews {
if type(of: view) == NSClassFromString("UISearchBarBackground"){
view.alpha = 0.0
}
}
or alternatively:
searchBar.barTintColor = UIColor.clear
searchBar.backgroundColor = UIColor.clear
searchBar.isTranslucent = true
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)