iOS11适配 - UINavigationBar上添加UISearchBar

咳咳,最近两天都在适配iOS11和iPhone X,在项目中遇到比较麻烦的一个适配是:在导航栏上添加的UISearchBar在iOS10及一下版本上显示一切正常,但是当我升级到了iOS11后,整个世界都不好了,导航栏上的UISearchBar不见了。

最终我还是成功的再iOS11上将UINavigationBar上的UISearchBar显示出来了,当然解决问题的这个过程还是很艰辛的,翻遍Google,Stack Overflow后终于找到了解决办法。再次记录下吧,希望能够帮助到同样遇到相同问题的各位开发者。

问题展示

先来一张图对比下iOS10和iOS11两个不同系统下,在导航栏中添加UISearchBar的情况,大家先感受下:

iOS11适配 - UINavigationBar上添加UISearchBar_第1张图片
iOS11以下版本

iOS11适配 - UINavigationBar上添加UISearchBar_第2张图片
iOS11

情况大概就是这么一个情况,在iOS11上导航栏上的搜索框不见了。

接下来来分析一下代码吧!

代码分析

UIView *titleView = [[UIView alloc] init];
titleView.py_x = PYSEARCH_MARGIN * 0.5;
titleView.py_y = 7;
titleView.py_width = self.view.py_width - 64 - titleView.py_x * 2;
titleView.py_height = 30;
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:titleView.bounds];
[titleView addSubview:searchBar];
titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = titleView;

一般来说都是这样将UISearchBar添加到导航栏上去的,先定义一个titleView,将UIsearchBar添加到titleView,然后将titleView赋值给self.navigationItem.titleView。

解决办法

将titleView的UIView重写为XUIView。

#import "XUIView.h"

@implementation XUIView

-(CGSize)intrinsicContentSize
{
    return UILayoutFittingExpandedSize;
}
@end

然后将上面的代码修改为:

UIView *titleView = [[XUIView alloc] init];
titleView.py_x = PYSEARCH_MARGIN * 0.5;
titleView.py_y = 7;
titleView.py_width = self.view.py_width - 64 - titleView.py_x * 2;
titleView.py_height = 30;
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:titleView.bounds];
[titleView addSubview:searchBar];
titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.navigationItem.titleView = titleView;

最后在iOS11上导航栏上的UISearchBar就显示出来了~~

你可能感兴趣的:(iOS11适配 - UINavigationBar上添加UISearchBar)