IOS7 when UIsearchbar added in UINavigationBar not showing cancel button

ios7uinavigationbaruisearchbar

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];

Best Answer

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;
Related Topic