似乎使用负内容偏移是要走的路。
我真的很喜欢 Demosthese 的想法,以跟踪最大的顶部插图。但是,这种方法存在一个问题。有时无法显示大标题,例如,当 iPhone 处于横向模式时。
如果在设备旋转到横向后使用此方法,则表格的偏移量将太大,因为导航栏中不显示大标题。
该技术的一个改进是仅在导航栏可以显示大标题时才考虑最大的TopSafeAreaInset。现在的问题是了解导航栏何时可以显示大标题。我在不同的设备上做了一些测试,当垂直尺寸类紧凑时,似乎没有显示大标题。
因此,Demosthese 解决方案可以通过以下方式改进:
class TableViewController: UITableViewController {
var biggestTopSafeAreaInset: CGFloat = 0
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
self.biggestTopSafeAreaInset = max(view.safeAreaInsets.top, biggestTopSafeAreaInset)
}
func scrollToTop(animated: Bool) {
if traitCollection.verticalSizeClass == .compact {
tableView.setContentOffset(CGPoint(x: 0, y: -view.safeAreaInsets.top), animated: animated)
} else {
tableView.setContentOffset(CGPoint(x: 0, y: -biggestTopSafeAreaInset), animated: animated)
}
}
}
还有一种情况可能会导致滚动后大标题不显示。
如果用户:
- 以横向模式旋转设备打开应用程序。
- 滚动视图。
- 纵向旋转设备。
此时 maximumTopSafeAreaInset 还没有机会找到最大值,如果调用 scrollToTop 方法,大标题将不会显示。幸运的是,这种情况不应该经常发生。