Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Change the title of cancel button in UISearchBar

I wish to change the title of the cancel button in iOS. I have been using this previously:

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller{
  self.searchDisplayController.searchBar.showsCancelButton = YES;
  UIButton *cancelButton = nil;
  for (UIView *subView in self.searchDisplayController.searchBar.subviews) {
     if ([subView isKindOfClass:NSClassFromString(@"UIButton")]) {
         cancelButton = (UIButton*)subView;
     }
  }
  [cancelButton setTitle:@"Annuller" forState:UIControlStateNormal];
}

But it doesnt seem to work in iOS7. Any Suggestions?

like image 555
Danienllxxox Avatar asked Sep 23 '13 09:09

Danienllxxox


Video Answer


2 Answers

You need to search for the button recursively. This should be a fail-safe way to do it:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self convertButtonTitle:@"Cancel" toTitle:@"Annuller" inView:self.searchBar];
}

- (void)convertButtonTitle:(NSString *)from toTitle:(NSString *)to inView:(UIView *)view
{
    if ([view isKindOfClass:[UIButton class]])
    {
        UIButton *button = (UIButton *)view;
        if ([[button titleForState:UIControlStateNormal] isEqualToString:from])
        {
            [button setTitle:to forState:UIControlStateNormal];
        }
    }

    for (UIView *subview in view.subviews)
    {
        [self convertButtonTitle:from toTitle:to inView:subview];
    }
}

I've tested this on iOS 7 only, but it works and should do so for iOS 6 too.

like image 122
Guy Kogus Avatar answered Oct 15 '22 18:10

Guy Kogus


simply do this code for it:-

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    /* when user start editing in serchbar 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;

}

Not test in iOS7 but this working fine in iOS6 hope this working for you.

OUTPUT IS:-

enter image description here

like image 40
Nitin Gohel Avatar answered Oct 15 '22 16:10

Nitin Gohel