Hide UISearchBar Background (iPhone SDK 3.2 & 4.0)

05/10/2010

Dear Non-Developer Readers,
I may start posting some technical stuff up here from time to time. I’ll try to not let it dominate my bi-annual blog posts. Also, I’m testing out this code highlighting plugin which seems to work pretty well.

My Problem:
I want to hide the background of a UISearchBar and the methods I found only worked on SDK versions 3.1.3 and below. That method basically grabs the subview (of class UISearchBarBackground) that contains the background image and sets it to hidden:

[[searchBar.subviews objectAtIndex:0] setHidden:YES];

Well that only works in versions of the iPhone SDK prior to 3.2. In 3.2 and beyond this technique no longer works (which is exactly why these sort of whatever.subviews hacks should generally be avoided).

My Solution:
In iPhone SDK 3.2 and 4.0 I’ve found this alternative technique that works:

[[searchBar.subviews objectAtIndex:0] removeFromSuperview];

And if you want to go all out and attempt to future-proof your code give this a try (no guarantee that it won’t still break though – Apple could still change the class name or change the structure of the UISearchBar in a future SDK update):

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

There are 3 comments in this article:

  1. On 07/26/2010 thankful said:

    thank you for this, it did save me time…

  2. On 08/20/2010 Grizzly said:

    However this doesn’t work with 3.2. When I use this code I get a black background. Do you know what could be the problem?

    I have my View that contains the search bar loaded from a nib.

    The connections to outlets are made properly.

  3. On 08/22/2010 Brandon said:

    Hi Grizzly,
    I just tested this out using a nib on an iPad app (iOS 3.2) instead of programmatically creating the interface and it works correctly for me. Without seeing your code I’m not sure what to suggest (but feel free to post it here).

Write a comment: