App-it.dk

Objective-C, iOS and Web.

Updated for iOS 7! Changing the Cancel-button Title in UISearchBar

Updated with iOS7 compatible code!

If you are writing a iOS app 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 searchDisplayControllerWillBeginSearch method and have it contain the following: iOS 7:

Change title of cancel-button in UISearchBar in iOS 7
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:@"Annuller" forState:UIControlStateNormal];
    }
}

iOS 5/6

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

The above code assumes that your class is a UISearchDisplayDelegate

Comments