iOS11 在键盘后面扩展 UIScrollView 插图

Extend UIScrollView insets behind keyboard on iOS11

自从 Apple 引入了 safe area insetsadjusted content insets 之后,已经可以使用的 UI 布局代码就被破坏了。在我的例子中 UIScrollView 底部插图在键盘出现时扩展:

func keyboardWillResize(_ notification: Notification) {
    let info: [AnyHashable: Any] = notification.userInfo!
    let keyboardTop = self.view.frameOnScreen.maxY - (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.y
    UIView.animate(withDuration: 0.3, animations: {
        self.tableView.contentInset.bottom = keyboardTop
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset
    })
}

在 iOS 11 内,此代码会在键盘出现时产生额外的插图,等于标签栏高度。很明显,因为现在 contentInset 仅表示用户定义的 insets,而真正的 insets 由 iOS 11.

中引入的 adjustedContentInset 表示

所以我的问题是如何妥善处理这个案子?可以选择写

self.tableView.contentInset.bottom = keyboardTop - self.tableView.adjustedContentInset.bottom

但它看起来很难看。也许有内置的方法来扩展键盘后面的插图?

显然,答案在官方文档中。我们应该将这些东西委托给视图控制器并处理它的安全区域插图,而不是手动调整内容插图。所以,这是工作代码:

func keyboardWillResize(_ notification: Notification) {
    let info: [AnyHashable: Any] = notification.userInfo!
    let keyboardTop = self.view.frameOnScreen.maxY - (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.y
    UIView.animate(withDuration: 0.3, animations: {
        self.additionalSafeAreaInsets.bottom = max(keyboardTop - self.view.safeAreaInsets.bottom, 0)
    })
}