Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS7 when UIsearchbar added in UINavigationBar not showing cancel button

Tags:

I add UISearchBar above UINavigationBar and set UIsearchbar showsCancelButton YES, work fine in iOS6 but in iOS7 not showing cancel button. I used below code snippet

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 600, 44)]; searchBar.showsCancelButton = YES; searchBar.translucent = NO; [searchBar setTintColor:[UIColor redColor]]; searchBar.backgroundColor = [UIColor yellowColor]; [self.navigationController.navigationBar   addSubview:searchBar]; 
like image 836
JackYi Avatar asked Sep 24 '13 15:09

JackYi


2 Answers

For some reason iOS7 does not show the cancel button when added to a navigation bar. This also happens if you try setting it as the titleView of a navigationItem.

You can circumvent this problem by wrapping the UISearchBar in another UIView first. Here's how I do it as a titleView:

UISearchBar *searchBar = [UISearchBar new]; searchBar.showsCancelButton = YES; [searchBar sizeToFit]; UIView *barWrapper = [[UIView alloc]initWithFrame:searchBar.bounds]; [barWrapper addSubview:searchBar]; self.navigationItem.titleView = barWrapper; 
like image 184
Rodskjegg Avatar answered Oct 01 '22 22:10

Rodskjegg


I had similar problem, on iPhone search bar with cancel button show well, but on iPad the cancel button wasn't shown. Wrapping the UIsearchBar to UIView like @Rodskjegg throw style issue. On iPad UIsearchBar setting it as the titleView of a navigationItem and add UIBarButtonItem to setRighttBarButtonItem as UIBarButtonSystemItemCancel.

    [self.navigationItem setLeftBarButtonItem:Nil animated:YES];     self.navigationItem.titleView = self.searchBar;      if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)      {         UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(searchBarCancelButtonClicked:)];          [self.navigationItem setRightBarButtonItem: cancelButton animated:YES];     }     else {         [self.navigationItem setRightBarButtonItem: nil animated:YES];     } 
like image 32
vcalfa Avatar answered Oct 01 '22 22:10

vcalfa