适配iOS 11<转>

一.bug展示

Xcode 升级到 9.0beta版本后,公司中的项目运行到iOS11的设备上出现了一个UI Bug,就像下面这种情况.


iOS11 模拟器

很显然,tableView有了额外的内边距.代码运行到之前的环境上是没问题的,可用Xcode9一编译,再跑到iOS11上就会出现这么严重的问题...

二.问题产生原因

先贴一段设置tableView的代码

private func setupTableView() {
        tableView = UITableView()
        tableView.frame = view.bounds
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.red
        // 公司的项目中导航栏是不透明的,所以需要加上这两行代码,我们自己来计算scrollView的内边距
        extendedLayoutIncludesOpaqueBars = true;
        automaticallyAdjustsScrollViewInsets = false;
        // 设置tableView的内边距(能够显示出导航栏和tabBar下覆盖的内容)
        tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
        // 设置内容指示器(滚动条)的内边距
        tableView.scrollIndicatorInsets = tableView.contentInset
}

关于extendedLayoutIncludesOpaqueBarsautomaticallyAdjustsScrollViewInsets

  • 这两个属性属于UIViewController
  • 默认情况下extendedLayoutIncludesOpaqueBars = false 扩展布局不包含导航栏
  • 默认情况下automaticallyAdjustsScrollViewInsets = true 自动计算滚动视图的内容边距
  • 但是,当 导航栏不透明时,而tabBar为透明的时候,为了正确显示tableView的全部内容,需要重新设置这两个属性的值,然后设置contentInset(参考代码).

上面的代码逻辑没有问题,但是放到iOS11 上为啥错了呢?
找了半天,点开了automaticallyAdjustsScrollViewInsets 这个属性,发现这个属性在iOS11过期了,如图:


automaticallyAdjustsScrollViewInsets.png


在OC的声明中,这个属性是这样的:
@property(nonatomic,assign) BOOL automaticallyAdjustsScrollViewInsets API_DEPRECATED_WITH_REPLACEMENT("Use UIScrollView's contentInsetAdjustmentBehavior instead", ios(7.0,11.0),tvos(7.0,11.0)); // Defaults to YES
这说明在iOS11 中, UIViewControllerautomaticallyAdjustsScrollViewInsets属性已经不再使用,我们需要使用UIScrollViewcontentInsetAdjustmentBehavior 属性来替代它.

关于contentInsetAdjustmentBehavior

@available(iOS 11.0, *)
public enum UIScrollViewContentInsetAdjustmentBehavior : Int {

    case automatic // Similar to .scrollableAxes, but will also adjust the top & bottom contentInset when the scroll view is owned by a view controller with automaticallyAdjustsScrollViewContentInset = YES inside a navigation controller, regardless of whether the scroll view is scrollable

    case scrollableAxes // Edges for scrollable axes are adjusted (i.e., contentSize.width/height > frame.size.width/height or alwaysBounceHorizontal/Vertical = YES)

    case never // contentInset is not adjusted

    case always // contentInset is always adjusted by the scroll view's safeAreaInsets
}

UIScrollViewContentInsetAdjustmentBehavior 是一个枚举类型,值有以下几种:

  • automaticscrollableAxes一样,scrollView会自动计算和适应顶部和底部的内边距并且在scrollView 不可滚动时,也会设置内边距.
  • scrollableAxes 自动计算内边距.
  • never不计算内边距
  • always 根据safeAreaInsets 计算内边距
    很显然,我们这里要设置为 never

三.开始适配

swift 中

private func setupTableView() {
        tableView = UITableView()
        tableView.frame = view.bounds
        tableView.dataSource = self
        tableView.delegate = self
        tableView.backgroundColor = UIColor.red

        extendedLayoutIncludesOpaqueBars = true;
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            automaticallyAdjustsScrollViewInsets = false;
        };
        tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0)
        tableView.scrollIndicatorInsets = tableView.contentInset
}

OC 中

self.extendedLayoutIncludesOpaqueBars = YES;
if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
        self.automaticallyAdjustsScrollViewInsets = NO;
}
_tableView.contentInset = UIEdgeInsetsMake(64, 0, 49, 0);
_tableView.scrollIndicatorInsets = _tableView.contentInset;


-------------------------------------------------------------------------------------------

导航栏

导航栏高度的变化

iOS11之前导航栏默认高度为64pt(这里高度指statusBar + NavigationBar),iOS11之后如果设置了prefersLargeTitles = YES则为96pt,默认情况下还是64pt,但在iPhoneX上由于刘海的出现statusBar由以前的20pt变成了44pt,所以iPhoneX上高度变为88pt,如果项目里隐藏了导航栏加了自定义按钮之类的,这里需要注意适配一下。

导航栏图层及对titleView布局的影响

iOS11之前导航栏的title是添加在UINavigationItemView上面,而navigationBarButton则直接添加在UINavigationBar上面,如果设置了titleView,则titleView也是直接添加在UINavigationBar上面。iOS11之后,大概因为largeTitle的原因,视图层级发生了变化,如果没有给titleView赋值,则titleView会直接添加在_UINavigationBarContentView上面,如果赋值了titleView,则会把titleView添加在_UITAMICAdaptorView上,而navigationBarButton被加在了_UIButtonBarStackView上,然后他们都被加在了_UINavigationBarContentView上,如图:

所以如果你的项目是自定义的navigationBar,那么在iOS11上运行就可能出现布局错乱的bug,解决办法是重写UINavigationBar的layoutSubviews方法,调整布局,上代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)layoutSubviews {
    [super layoutSubviews];
     
    //注意导航栏及状态栏高度适配
    self.frame = CGRectMake(00, CGRectGetWidth(self.frame), naviBarHeight);
    for (UIView *view in self.subviews) {
        if([NSStringFromClass([view class]) containsString:@"Background"]) {
            view.frame = self.bounds;
        }
        else if ([NSStringFromClass([view class]) containsString:@"ContentView"]) {
            CGRect frame = view.frame;
            frame.origin.y = statusBarHeight;
            frame.size.height = self.bounds.size.height - frame.origin.y;
            view.frame = frame;
        }
    }
}

再补充一点,看了简书App适配iOS11发现titleView支持autolayout,这要求titleView必须是能够自撑开的或实现了- intrinsicContentSize方法

1
2
3
- (CGSize)intrinsicContentSize {
    return UILayoutFittingExpandedSize;
}

UIScrollView、UITableView、UICollectionView

大家在iOS11设备上运行出现最多问题应该就是tableview莫名奇妙的偏移20pt或者64pt了。。原因是iOS11弃用了automaticallyAdjustsScrollViewInsets属性,取而代之的是UIScrollView新增了contentInsetAdjustmentBehavior属性,这一切的罪魁祸首都是新引入的safeArea,关于safeArea适配这篇文章iOS 11 安全区域适配总结讲的很详细,感兴趣的可以看下,我直接贴适配代码,因为低版本直接用contentInsetAdjustmentBehavior会报警告,所有定义了如下的宏(感谢@炒鸡范的指正,之前的宏犯了个低级错误...现改为)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#define  adjustsScrollViewInsets(scrollView)
do {
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored "-Warc-performSelector-leaks"")
if ([scrollView respondsToSelector:NSSelectorFromString(@"setContentInsetAdjustmentBehavior:")]) {
    NSMethodSignature *signature = [UIScrollView instanceMethodSignatureForSelector:@selector(setContentInsetAdjustmentBehavior:)];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    NSInteger argument = 2;
    invocation.target = scrollView;
    invocation.selector = @selector(setContentInsetAdjustmentBehavior:);
    [invocation setArgument:&argument atIndex:2];
    [invocation retainArguments];
    [invocation invoke];
}
_Pragma("clang diagnostic pop")
while (0)

还有的发现某些界面tableView的sectionHeader、sectionFooter高度与设置不符的问题,在iOS11中如果不实现 -tableView: viewForHeaderInSection:和-tableView: viewForFooterInSection: ,则-tableView: heightForHeaderInSection:和- tableView: heightForFooterInSection:不会被调用,导致它们都变成了默认高度,这是因为tableView在iOS11默认使用Self-Sizing,tableView的estimatedRowHeight、estimatedSectionHeaderHeight、 estimatedSectionFooterHeight三个高度估算属性由默认的0变成了UITableViewAutomaticDimension,解决办法简单粗暴,就是实现对应方法或把这三个属性设为0。

如果你使用了Masonry,那么你需要适配safeArea

1
2
3
4
5
if (@available(iOS 11.0, *)) {
    make.edges.equalTo()(self.view.safeAreaInsets)
else {
    make.edges.equalTo()(self.view)
}

iPhoneX

LaunchImage

关于iPhoneX(我就不吐槽刘海了...),如果你的APP在iPhoneX上运行发现没有充满屏幕,上下有黑色区域,那么你应该也像我一样LaunchImage没有用storyboard而是用的Assets,解决办法如图,启动图的尺寸为1125x2436,or you can iOS开发时如何使用 Launch Screen Storyboard

TabBarController

因为我们的项目用了第三方的TabBarController,在iPhoneX运行,tabBar看起来怪怪的...估计作者要等到猴年马月才适配iPhoneX,项目又着急上线,就自己修改了第三方,主要是tabBar高度及tabBarItem偏移适配,iPhoneX由于底部安全区的原因UITabBar高度由49pt变成了83pt,可以通过判断机型来修改相关界面代码

1
#define kDevice_Is_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(11252436), [[UIScreen mainScreen] currentMode].size) : NO)
原文地址:https://www.cnblogs.com/deng37s/p/7595057.html