Reputation: 254
I have set background image for searchbar and search field using the code below. I am using Xcode5 DP2 and ios 7.
[[UISearchBar appearance] setSearchFieldBackgroundImage:[UIImage imageNamed:@"fieldBg"] forState:UIControlStateNormal];
[[UISearchBar appearance] setBackgroundImage:[UIImage imageNamed:@"searchBarBg"]];
This code works fine. But I want to customize the cancel button image also. For that I have used the following code in the viewWillAppear and searchBarTextDidBeginEditing. It works for the first time while loading.
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 clicks one time, then the custom image won't come there after. I logged the _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 understood that the cancel button is not coming under the subviews where I am checking. I tried the above code in all possible delegate methods but wasn't able to solve the issue.
Upvotes: 7
Views: 2572
Reputation: 54
You can use [self setShowsCancelButton:NO animated:NO];
in layoutSubviews
function and add a custom UIButton
to the place you like.
You just have to take the pain of writing code for the functionality of your cancel button.
Upvotes: 2