关于iOS 11的一些新特性适配实践总结

2020-01-21 02:15:03王旭

此外还可以给 navigation item 中的属性 hidesSearchBarWhenScrolling 设置为 true, 他可以使你 view controller 中管理的 scroll view 在滑动的时候自动隐藏 search bar.

Scroll view

如果使用过 view controller 管理过 scroll view 的话,想必对 automaticallyAdjustsScrollViewInsets 这个属性一定不陌生。在 iOS 11 之前,该属性可以让 view controller 自动管理 scroll view 中的 content inset. 但是,在实际在开发的过程中,这样的自动管理的方式会带来麻烦,尤其是一些在 content inset 需要动态调整的情况。

为此,在 iOS 11, UIKit 废弃了 automaticallyAdjustsScrollViewInsets 属性,并将该的职责转移到 scroll view 本身。因此,在 iOS 11 中,为了解决这个问题,有两个 scroll view 的新属性。一个是用于管理调整 content inset 行为的属性 contentInsetAdjustmentBehavior, 另一个是获取调整后的填充的属性 adjustedContentInset. 同时,UIScrollViewDelegate 也提供了新的代理方法,以方便开发者获取 inset 变化的时机:


optional func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView)

至此,对于这个「自动为开发者设置 inset」 的特性,苹果算是提供了相当完备的接口了。

不过作为开发者的我们要注意的是,如果对原本自动设置 contentInset 属性的行为有依赖,在新的 iOS 11 的适配中,可能得做出调整。

此外,为了便于开发者在 scroll view 中使用 Auto Layout. UIKit 还提供了两个新的属性。一个是 contentLayoutGuide, 它用来获取当前在 scroll view 内的内容的 layout guides. 而另一个是 frameLayoutGuide, 他用来获取实际内容的 layout guides. 这样说有点繁琐,还是看 WWDC 的原图吧:

ios11新特性适配,ios11新特性,ios11适配

Table view

实际上对于 table view 而言,其最大的更新就在于新的特性 Drag and Drop 了吧。但是这个特性在适配中暂时不需要考虑,本文就不介绍了,让我们一起来看看其他有意思的变化。

首先是在 iOS 11 中,table view 默认开启了 self-sizing, 可以注意到 estimatedRowHeight, estimatedSectionHeaderHeight 以及 estimatedSectionFooterHeight 都被默认设置为 UITableViewAutomaticDimension. 但是我们知道,如果原本已经实现 tableView:heightForRowAtIndexPath: 之类的方法并返回了高度,那么在布局方面是不会有影响的,这对 iOS 11 适配而言是个好消息。

在 iOS 11 中,有了新的 layout margins 的概念,因此 UIKit 也为 separator inset 做了额外的补充。现在 separator inset 可以有两个来源,一个是从 cell 的边缘开始 (UITableViewSeparatorInsetReference.fromCellEdges) ,另一个是从 table view 默认的填充开始 (UITableViewSeparatorInsetReference.fromAutomaticInsets)。其中,默认的填充由 table view 的 layout margins 进行控制。