前言
iOS11導(dǎo)航欄除了新加入了largeTitles和searchController兩個(gè)新特性,可能是加入largeTitles的原因其結(jié)構(gòu)較iOS 10發(fā)生了些變化采幌。
iOS11之前導(dǎo)航欄的navigationBarButton則直接添加在navigationBar上面
在iOS11之后恍涂,蘋果添加了新的類來管理,可以看到titleView直接加在_UINavigationBarContentView上植榕,UIBarButtonItem則添加在_UIButtonBarStackView上面再沧,而_UIButtonBarStackView則添加在_UINavigationBarContentView上面,最后添加到UINavigationBar上面尊残,如下圖所示:
由于結(jié)構(gòu)的變化炒瘸,在iOS 11中我們自定義設(shè)置leftBarButtonItem淤堵,其點(diǎn)擊區(qū)域變得很小,讓人點(diǎn)的很焦灼顷扩,如下圖綠色區(qū)域所示:
具體代碼如下拐邪,設(shè)置的frame在這里并沒有什么卵用,點(diǎn)擊區(qū)域依然只有圖片原本的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;
為了能增加點(diǎn)擊區(qū)域隘截,我們就需要增加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設(shè)置為titleview婶芭,會(huì)導(dǎo)致navigation的高度發(fā)生異常(ps:push到下一個(gè)界面东臀,下個(gè)界面的view距離navigation出現(xiàn)了一段黑色區(qū)域)需要處理下:
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;
詳細(xì)資料參考:
https://stackoverflow.com/questions/45997996/ios-11-uisearchbar-in-uinavigationbar