I tried:
UITextField *searchtextfield = [searchBar.subviews objectAtIndex:1];
UIButton *cButton = [UIButton buttonWithType:UIButtonTypeCustom];
cButton.frame = CGRectMake(0, 0, 20 , 20);
cButton.backgroundColor = [UIColor clearColor];
[cButton setImage:[UIImage imageNamed:@"x-button"] forState:UIControlStateNormal];//your button image.
cButton.contentMode = UIViewContentModeScaleToFill;
[cButton addTarget:self action:@selector(xButtonPressed) forControlEvents:UIControlEventTouchUpInside];//This is the custom event
[searchtextfield setRightView:cButton];
[searchtextfield setRightViewMode:UITextFieldViewModeWhileEditing];
But it doesn't work very well... It displays custom button, but when you type something, the old one get's back...
How can I do this?
If you want to set a custom clear button in a UISearchBar try this:
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"MyClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
Don't forget to set an image for UIControlStateHighlighted
[[UISearchBar appearance] setImage:[UIImage imageNamed:@"HighlightedClearButton.png"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
You need the following
[searchBar setImage:[UIImage imageNamed:@"image1"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateHighlighted];
[searchBar setImage:[UIImage imageNamed:@"image2"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
It is strongly recommended to place strings in this order starting from UIControlStateHighlighted in case you want to use the same image: image1=image2=image.
In iOS7 it is weird but fact that direct order of UIControlStateNormal and UIControlStateHighlighted doesn't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With