Objective-c – Change Cancel Button BackgroundColor and Text of UISearchBar in iOS7

cocoa-touchios7iphoneobjective cuisearchbar

I have the following code that changes the background of the Cancel button in the UISearchBar.

for( UIView *subview in self.searchBar.subviews ){
    if ([subview isKindOfClass:[UIButton class]]) {
        [(UIButton *)subview setEnabled:YES];
        [(UIButton *)subview setTitle:@"New Button Text" forState:UIControlStateNormal];
        ((UIButton *)subview).tintColor = [UIColor colorWithRed:4/255.0 green:119/255.0 blue:152/255.0 alpha:1.0];
    }
}

The problem is that this code does not work in iOS7! What changed in the structure of the views in the UISearchBar?

Edit: Tested here and this is the new Hierarchy of the UISearchBar:

UISearchBar:
---UIView:
------UISearchBarBackground
------UISearchBarTextField
------UINavigationButton

The problem is that i cannot test if ([sub isKindOfClass:[UINavigationButton class]]). This line throws a compile error: Use of undeclared identifier: UINavigationButton

Best Answer

[Edited]

Try this codes.

Add in AppDelegate if you want to change all cancel button.

[[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                                      [UIColor redColor],
                                                                                                      UITextAttributeTextColor,
                                                                                                      [UIColor whiteColor],
                                                                                                      UITextAttributeTextShadowColor,
                                                                                                      [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                                                      UITextAttributeTextShadowOffset,
                                                                                                      nil]
                                                                                            forState:UIControlStateNormal];

In iOS7 , we need to add objectAtIndex:0 and subviews.

The searchBar sub views hierarchy has been changed in iOS7, try the below:

in iOS7:

NSArray *searchBarSubViews = [[self.searchBar.subviews objectAtIndex:0] subviews];


iOS6 and before:

NSArray *searchBarSubViews =  self.searchBar.subviews;
Related Topic