iOS7在UINavigationBar中添加UIsearchbar时未显示取消按钮

问题描述:

我在UINavigationBar上面添加UISearchBar并设置UIsearchbar showsCancelButton YES,在iOS6中正常工作但在iOS7中没有显示取消按钮。
我在下面的代码片段中使用

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


出于某种原因,iOS7不显示取消按钮添加到导航栏。如果您尝试将其设置为navigationItem的titleView,也会发生这种情况。

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.

您可以通过先将UISearchBar包装在另一个UIView中来解决此问题。以下是我作为titleView的方式:

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;