Updated for iOS7, If you are writing a iOS application that contains of UITableView along with a UISearchBar, you might want to change the title of the cancel button, i.e. if you’re localizing your app.

But the cancel button isn’t that trivial to get a hold of. Here is some code that allows you to change the title:
Implement the


1
searchDisplayControllerWillBeginSearch

method and have it contain the following:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    /* when user start editing in search bar this method will display cancel button and disable the autocorrection functionality */

    srcbar.showsCancelButton = YES;

    for (UIView *subView in searchBar.subviews) {
        if ([subView isKindOfClass:[UIButton class]]) {
           UIButton *cancelButton = (UIButton*)subView;

            [cancelButton setTitle:@"hi" forState:UIControlStateNormal];
        }
    }
    srcbar.autocorrectionType = UITextAutocorrectionTypeNo;

}

The above code assumes that your class is a


1
UISearchDisplayDelegate

This is the Output:

This post was developed further with the help from Stackoverflow and the image also supplied by user: Nitin Gohel

If you’re using iOS7 the following code will do the trick:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
    self.searchDisplayController.searchBar.showsCancelButton = YES;
    UIButton *cancelButton;
    UIView *topView = self.searchDisplayController.searchBar.subviews[0];
    for (UIView *subView in topView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UINavigationButton")]) {
            cancelButton = (UIButton*)subView;
        }
    }
    if (cancelButton) {
      //Set the new title of the cancel button
        [cancelButton setTitle:@"Hi" forState:UIControlStateNormal];
    }
}

Check out the beginners guide to objective-c if you would like to strengthen your knowledge and start your journey in becoming an iOS Developer

Problems?

We have a new Questions and Answers section so you can get help from the awesome community.

Ask a Question

Enjoyed this post?

Subscribe to our RSS Feed or Follow us on twitter to keep up to date with the latest from iOS-Blog. Remember, Sharing is caring so please click one of the following options:

Tags: , , , ,