Tomasz Szulc
Tomasz Szulc

Reputation: 4235

How to customize UISearchBar in iOS7 (Clear button)

I'm trying to customise the UISearchBar clear button. I can set a custom image for the icon in normal state but I don't know how to set the same image for the state when I've got a finger on the button. It always has the system look. I tried to set the same image for all available states but failed to obtain any results.

for iOS7:

    [self.searchBar setImage:[UIImage imageNamed:@"icon_X_black.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [self.searchBar setImage:[UIImage imageNamed:@"icon_X_black.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted]; /// doesn't work

No changes when I set the same for UIControlStateHighlighted or UIControlStateSelected. Is it possible to customise this button in iOS7? In iOS6 when I set the same icon for UIControlStateHighlighted it works correctly.

for iOS6:

    [self.searchBar setImage:[UIImage imageNamed:@"icon_X_black.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [self.searchBar setImage:[UIImage imageNamed:@"icon_X_black.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted]; /// it works

Thank you in advance.

Upvotes: 1

Views: 2440

Answers (2)

Guido Hendriks
Guido Hendriks

Reputation: 5776

From the documentation on UISearchBar:

state

A control state.

Valid states are UIControlStateNormal and UIControlStateDisabled.

Seems like UIControlStateHighlighted isn't supported here.

Upvotes: 2

malex
malex

Reputation: 10096

It is very strange behavior of iOS7 but the solution is the reverse order of statements in code if you want to set the same image for two states

[self.searchBar setImage:[UIImage imageNamed:@"icon_X_black"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[self.searchBar setImage:[UIImage imageNamed:@"icon_X_black"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];

Also you can duplicate you icon_X_black file under different names and use any order.

Upvotes: 6

Related Questions