0

I am using below code. It is working perfectly in IOS 6.x. building from Xcode 4.6.x . But that code is not working no more in IOS 7.x building from xcode 5.x.

My objective is to display a custom image in place of cancel button of UISearchBar when user start editing in UISearchBar.

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    UIButton *cancelButton = nil;
    for(UIView *subView in searchBar.subviews){
        if([subView isKindOfClass:UIButton.class]){
            cancelButton = (UIButton*)subView;
        }
    }
    [cancelButton setTintColor:[UIColor colorWithRed:167.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:1.0f]];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"customKeyboardIcon.png"] forState:UIControlStateNormal];
    [cancelButton setTitle:nil forState:UIControlStateNormal];
}
NSCry
  • 1,662
  • 6
  • 23
  • 39
  • Check this post. it may help you http://stackoverflow.com/questions/19206757/how-to-change-textcolor-of-cancel-button-of-uisearchbar-in-ios7 – Khaled Annajar Jan 28 '14 at 18:02

2 Answers2

6

The cancel button in the UISearchBar is of type UIBarButton. They way I did it was the following (works on iOS 5,6,7) :

 [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setBackgroundImage:cancelButtonImage forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

If you don't want the custom cancel button on all of you UISearchBars, just create a custom UISearchBar class and replace the appearanceWhenContainedIn:[UISearchBar class] with your new custom made class.

For removing the text:

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@""];

As for the image, either you adjust your image resource, or you create an UIImage with some insets, (tinker with the insert until you get the expected result):

     UIImage *cancelButtonImage = [UIImage imageNamed:SEARCH_BAR_CANCEL_BUTTON];
cancelButtonImage = [cancelButtonImage resizableImageWithCapInsets:CANCEL_BUTTON_IMAGE_INSETS];
Durican Radu
  • 1,327
  • 11
  • 12
0

Check this code I use:

-(void) colorCancelButton
{
    UIButton *cancelButton = [self getCancelButton];
        [cancelButton setTintColor:[Util colorFromHex:@"#D6D1CF"]];
        [cancelButton setTitleColor:[Util colorFromHex:@"333333"] forState:UIControlStateNormal];
}

-(UIButton*) getCancelButton
{
    UIButton *cancelButton = nil;
    for(UIView *subView in self.subviews){
        if([subView isKindOfClass:UIButton.class])
        {
            cancelButton = (UIButton*)subView;
        }
    }
    return cancelButton;
}
Khaled Annajar
  • 15,542
  • 5
  • 34
  • 45