Vikram
Vikram

Reputation: 311

Make UISearchBar background clear

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 made clear background of searchbar

 for (UIView *subview in self.searchBarHome.subviews) {
      if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
         [subview removeFromSuperview];//please help me to make clear background of uisearchbar
        break; 
    }
}
[self.searchBarHome setBackgroundColor:[UIColor clearColor]];

Upvotes: 31

Views: 35693

Answers (19)

Vivek
Vivek

Reputation: 100

On iOS 17, Xcode 15,

If you want to change from

UIsearchbar default ui appearance

to

Ui SearchBar appearance needed

I used the following code

        self.barSearch.barTintColor = .white
        self.barSearch.isTranslucent = false
        self.barSearch.backgroundColor = .white
        self.barSearch.searchTextField.backgroundColor = .white
        self.barSearch.layer.borderWidth = 2
        self.barSearch.layer.borderColor = UIColor.white.cgColor

Along with in Storyboard, Search Style - Prominent and Bar Style - Default

Upvotes: -1

andrewlundy_
andrewlundy_

Reputation: 1143

Swift 5.4, iOS 14.5.

Here is the default UISearchBar, on top of a white background: enter image description here

And the same setup on top of a grey background: enter image description here

To make the background of the search bar clear, set the search bar style to minimal. This removes the search bar's background and makes the search field translucent.
searchBar.searchBarStyle = .minimal

enter image description here

enter image description here

Then, set the search text field's background color to whatever you want. In this case, I've set it to white. searchBar.searchTextField.backgroundColor = .white

You can see the result of this here: enter image description here

enter image description here

If you set searchBar.searchTextField.backgroundColor = .red: enter image description here

Upvotes: 0

Kawe
Kawe

Reputation: 699

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.

Upvotes: 5

Get Schwifty
Get Schwifty

Reputation: 171

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

Upvotes: 0

Vitya Shurapov
Vitya Shurapov

Reputation: 2318

searchBarStyle = .default
searchTextField.backgroundColor = .yourColor

With this combination, you can remove the gray background of searchTextField and set yours!

Upvotes: 0

humbleCoder
humbleCoder

Reputation: 473

Oh man! I've been looking everywhere for a solution and trying multiple things. As @gmogames had mentoned above you can use any of these answers, but make sure the Search Bar Style is set to default or it won't work. So, to clarify on the solution this is what worked for me:

Set Search Bar Style to default in the Storyboard or code(wherever you created the UISearchBar. Then add this code to your view controller:

mySearchBar.searchTextField.backgroundColor = .clear

Upvotes: 1

Derek Soike
Derek Soike

Reputation: 11680

If you want to change this...

enter image description here

To this...

enter image description here

Use:

self.searchBar.searchTextField.backgroundColor = .clear

Upvotes: 10

Romulo BM
Romulo BM

Reputation: 751

Simply use searchBar.searchBarStyle = .minimal works for me.

I had used many workarounds for a long time, until i discover this property accidentally, and works like a charm.

Upvotes: 10

Johnson
Johnson

Reputation: 243

For iOS 12, swift 4.x A bit too hacky but Debug view hierarchy shows _UISearchBarSearchFieldBackgroundView is responsible to the background color. To get to it, ...

for subview in searchBar.subviews.last!.subviews {
   if subview.isKind(of: NSClassFromString("UISearchBarTextField")!) {
       for v in subview.subviews {
          if v.isKind(of: NSClassFromString("_UISearchBarSearchFieldBackgroundView")!) {
                  v.removeFromSuperview()
                }
            }
        }
    }

This is all too hacky. I prefer asking designer to accept Apple default color.

Upvotes: 0

ChanOnly123
ChanOnly123

Reputation: 1034

extension UISearchBar {
    func changeSearchBarColor(fieldColor: UIColor, backColor: UIColor, borderColor: UIColor?) {
        UIGraphicsBeginImageContext(bounds.size)
        backColor.setFill()
        UIBezierPath(rect: bounds).fill()
        setBackgroundImage(UIGraphicsGetImageFromCurrentImageContext()!, for: UIBarPosition.any, barMetrics: .default)

        let newBounds = bounds.insetBy(dx: 0, dy: 8)
        fieldColor.setFill()
        let path = UIBezierPath(roundedRect: newBounds, cornerRadius: newBounds.height / 2)

        if let borderColor = borderColor {
            borderColor.setStroke()
            path.lineWidth = 1 / UIScreen.main.scale
            path.stroke()
        }

        path.fill()
        setSearchFieldBackgroundImage(UIGraphicsGetImageFromCurrentImageContext()!, for: UIControlState.normal)

        UIGraphicsEndImageContext()
    }
}

Upvotes: 4

ivoroto
ivoroto

Reputation: 1035

My solution working on Swift 4.1 | iOS 11.4 where I change the background and text colors of UISearchBar

enter image description here

The key is to find the UISearchBar's UITextField component and to change its parameters:

let searchTextField = searchBar.value(forKey: "searchField") as? UITextField
searchTextField?.textColor = UIColor.white
searchTextField?.backgroundColor = UIColor.red
searchTextField?.attributedPlaceholder =  NSAttributedString(string: "Your Placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white.withAlphaComponent(0.5)])

Then I set the "search" and the "clear" image

//search image
searchBar.setImage(UIImage(named: "icon_search"), for: UISearchBarIcon.search, state: .normal)
//clear image
searchBar.setImage(UIImage(named: "icon_search_clear"), for: UISearchBarIcon.clear, state: .normal)

Upvotes: 4

gmogames
gmogames

Reputation: 3081

For anyone coming here and not being able to make the remove or alpha solution work for you, make sure you have your searchBar SearchStyle NOT on MINIMALIST. Change it to Default and use any of the codes provided here

Upvotes: 6

Eden
Eden

Reputation: 1820

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)

Upvotes: 28

Rog
Rog

Reputation: 18670

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.

Upvotes: 11

Scarafone
Scarafone

Reputation: 116

Setting the backgroundColor and barTintColor did not work me iOS 9+, left me with a black background. However Ruozi solution will work. Here is a swift version of the same code.

for view in _searchBar.subviews.last!.subviews {
    if view.isKindOfClass(NSClassFromString("UISearchBarBackground")!) {
        view.removeFromSuperview()
    }
}

Upvotes: 4

Andrew2M
Andrew2M

Reputation: 248

Removing the UISearchBarBackground may result in unknown behavior particularly if as you begin to use the element in more advanced ways.

Ruozi's answer was my preferred solution for grabbing the UISearchBarBackground element however I would suggest setting the alpha to 0 rather than removing the view with the following:

for (UIView *subview in [[self.searchBar.subviews lastObject] subviews]) {
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview setAlpha:0.0];
        break;
    }
}

Add the above code to your UIViewController subclass that contains an IBOutlet *searchBar. This code snippet will acheive a transparent background for both iOS8 and iOS9.

In addition it may be better design decision to include this code in your UISearchBar subclass in order to avoid cluttering your viewController.

Upvotes: 13

Ruozi
Ruozi

Reputation: 171

UISearchBar includes two subviews,they are 'UISearchBarBackground' and 'UITextField'. In IOS8, you need to remove 'UISearchBarBackground' to clear it.

for (UIView *subview in [[yourSearchBar.subviews lastObject] subviews]) {        
    if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) {
        [subview removeFromSuperview];
        break;
    }
}

Upvotes: 16

staticVoidMan
staticVoidMan

Reputation: 20274

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];

Upvotes: 44

ldindu
ldindu

Reputation: 4380

Subclass the uisearchbar and override initWithFrame and initWithCoder method and set the background color as

// For searchbar created programmatically
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self configureSetup];
    }
    return self;
}

// For search bar created on xib
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self configureSetup];
    }
    return self;
}

- (void)configureSetup
{
    self.backgroundColor = [UIColor clearColor];
}

and use the subclassed searchbar instead in place where you specified UISearchBar

Upvotes: 1

Related Questions