iOS 11 导航栏问题

前言

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,200评论 4 61
  • iOS 11适配源码 Demo地址 安全区域的适配 用Xcode 9 创建storyboard或者xib时,最低版...
    Bytesking阅读 6,581评论 5 24
  • 我爱你
    毁灭阅读 299评论 0 0
  • 二月春意东风晚 街柳吐芽却不迟
    天马行空a阅读 170评论 0 0