UISearchbar custom cancel button image

I set the background image for the search and search bar using the following code. I am using Xcode5 DP2 and ios 7.

[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"fieldBg"] forState:UIControlStateNormal]; [[UISearchBar appearance] setBackgroundImage:[UIImage imageNamed:@"searchBarBg"]]; 

This code is working fine. But I also want to customize the cancel button image. For this, I used the following code in viewWillAppear and searchBarTextDidBeginEditing. It works for the first time at boot.

 for (UIView *searchbuttons in _searchBar.subviews) { if ([searchbuttons isKindOfClass:[UIButton class]]) { UIButton *cancelButton = (UIButton*)searchbuttons; cancelButton.enabled = YES; [cancelButton setBackgroundImage:[UIImage imageNamed:@"cancelImage"] forState:UIControlStateNormal]; break; } } 

If the cancel button is pressed once, then the custom image will not appear after that. I registered _searchBar.subviews and got the results as

 po [_searchBar subviews] <__NSArrayM 0x210b1120>( <UISearchBarBackground: 0x1fd6ff80; frame = (0 0; 768 44); userInteractionEnabled = NO; layer = <CALayer: 0x1fdafaf0>>, <UISearchBarTextField: 0x1fd6f2f0; frame = (5 -3; 758 50); text = ''; clipsToBounds = YES; opaque = NO; gestureRecognizers = <NSArray: 0x1fdc10b0>; layer = <CALayer: 0x1fd6f480>> ) 

From this, I realized that the cancel button does not fall under the subzones where I check. I tried the above code in all possible delegation methods, but could not solve the problem.

+7
iphone uitableview xcode5 uisearchbar uisearchdisplaycontroller
source share
1 answer

You can use [self setShowsCancelButton:NO animated:NO]; into the layoutSubviews function and add a custom UIButton to the desired location. You just need to take the pain of writing code for the functionality of the cancel button.

+2
source share