iOS 11从UITableView或UIScrollView获取visibleHeight和contentInset

zir*_*isp 8 ios swift swift4 ios11

在iOS 10之前

如果我想得到一个表或滚动视图的可见高度,我不得不从tableview的高度减去顶部和底部插入

let tableView = ....
let height = tableView.frame.size.height - tableView.contentInset.top - tableView.contentInset.bottom
Run Code Online (Sandbox Code Playgroud)

iOS 11

不幸的是,在iOS 11上使用上述方法,我得不到正确的值.

经过一些调试后,我意识到顶部插入是0.0,而不是导航栏的高度.

zir*_*isp 6

iOS 11和UIScrollViewContentInsetAdjustmentBehavior

我没有得到正确的contentInset,因为iOS 11引入了UIScrollViewContentInsetAdjustmentBehavior.可在以下链接中找到更多信息:

https://developer.apple.com/documentation/uikit/uiscrollview/2902261-contentinsetadjustmentbehavior

由于UIScrollViewContentInsetAdjustmentBehavior介绍,我们必须考虑到adjustedContentInset属性,并将其添加到contentInset.

以上代码必须更新为以下内容:

let visibleHeigh: CGFloat
if #available(iOS 11, *) {
  visibleHeight = tableView.frame.size.height - (tableView.contentInset.top + tableView.adjustedContentInset.top) - (tableView.contentInset.bottom + tableView.adjustedContentInset.bottom)
} else {
  visibleHeight = tableView.frame.size.height - tableView.contentInset.top - tableView.contentInset.bottom
}
Run Code Online (Sandbox Code Playgroud)


Luc*_*hwe 5

如果希望滚动视图的内容插图不受“ adjustedContentInset”的影响,则可以使用以下代码禁用此不可预测的行为:

// obj-c
if (@available(iOS 11.0, *)) {
  [tableView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
}

// swift
if #available(iOS 11.0, *) {
  tableView.contentInsetAdjustmentBehavior = .never
}
Run Code Online (Sandbox Code Playgroud)