前言
iOS11导航栏除了新加入了largeTitles和searchController两个新特性,可能是加入largeTitles的原因其结构较iOS 10发生了些变化。
iOS11之前导航栏的navigationBarButton则直接添加在navigationBar上面
image.png
在iOS11之后,苹果添加了新的类来管理,可以看到titleView直接加在_UINavigationBarContentView上,UIBarButtonItem则添加在_UIButtonBarStackView上面,而_UIButtonBarStackView则添加在_UINavigationBarContentView上面,最后添加到UINavigationBar上面,如下图所示:
image.png
由于结构的变化,在iOS 11中我们自定义设置leftBarButtonItem,其点击区域变得很小,让人点的很焦灼,如下图绿色区域所示:
image.png
具体代码如下,设置的frame在这里并没有什么卵用,点击区域依然只有图片原本的size那么大:
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 40)];
[btn setImage:imageWhite forState:UIControlStateNormal];
[btn addTarget:self action:@selector(bpBack) forControlEvents:UIControlEventTouchUpInside];
btn.backgroundColor = [UIColor greenColor];
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
leftItem.width = 60;
self.navigationItem.leftBarButtonItem = leftItem;
为了能增加点击区域,我们就需要增加button的size,然后就想到通过改变ContentEdgeInsets来增大button的size,
...
...
btn.backgroundColor = [UIColor greenColor];
if (@available(iOS 11.0,*)) {
[btn setContentMode:UIViewContentModeScaleToFill];
[btn setContentEdgeInsets:UIEdgeInsetsMake(0, 5, 5, 20)];
}
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
...
...
另:searchBar设置为titleview,会导致navigation的高度发生异常(ps:push到下一个界面,下个界面的view距离navigation出现了一段黑色区域)需要处理下:
CGRect frame = CGRectMake(0, 0, 150, 44);
UISearchBar *search = [[UISearchBar alloc] initWithFrame:frame];
search.placeholder = @"搜索";
search.delegate = self;
UITextField *searchField=[search valueForKey:@"_searchField"];
searchField.backgroundColor = [UIColor groupTableViewBackgroundColor];
// --- iOS 11异常处理
if(@available(iOS 11.0, *)) {
[[search.heightAnchor constraintEqualToConstant:44] setActive:YES];
}
self.navigationItem.titleView = search;
详细资料参考:
https://stackoverflow.com/questions/45997996/ios-11-uisearchbar-in-uinavigationbar