Search code examples
iosobjective-ciphonecocoa-touchuisearchbar

Styling the cancel button in a UISearchBar


I have a UISearchBar that has a cancel button (it's displayed using -(void)setShowsCancelButton:animated). I've changed the tintColor of the search bar like this in an attempt to get a grayish searchbar:

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
searchBar.tintColor = [UIColor colorWithWhite:0.8 alpha:1.0];

This is what it looks like now - notice how the cancel button is also gray: http://twitpic.com/c0hte

Is there a way to set the color of the cancel button separately so it looks more like this: http://twitpic.com/c0i6q


Solution

  • What you want to do is pretty tough. There is no built-in hook to get at the cancel button.

    However, there are a couple of options if you are willing to jimmy open the hood.

    First off, UISearchBar is a UIView, and the Cancel button is also a view, which is added into the search bar as a subview, just as you would expect.

    I have experimented a little, and can tell you that when the button is onscreen it has a size of 48,30.

    So in viewWillAppear, you can do something like this:

    1. Find the cancel button view in [searchBar subviews] by looking for one with size 48,30. (There only seems to be one -- this could change...) You could be doubly careful and look for one that is in approximately the correct position (differs in landscape and portrait).

    2. Add a subview to the cancel button.

    3. The subview should be a UIControl (so that you can set enabled = NO, in order to make sure touch events get to the actual cancel button)

    4. It needs to have the right color and rounded corners; you will need to fudge the size for reasons I don't yet understand (55,30 seems to work)

    5. This will work if searchBar.showsCancelButton is always YES; if you want it to disappear when not editing the search string, you will need to find a hook to add the overlay each time the cancel button appears.

    6. As you can see, this is some ugly tinkering. Do it with eyes wide open.