如何让TableView最后一行底部贴合底部及禁止到达底部后继续滚动?
我来帮你搞定这两个TableView的问题哈~
我猜你说的是当TableView的内容总高度小于自身高度时,想让最后一行单元格贴紧TableView底部的场景?给你两个实用的实现方式:
方法一:用
tableFooterView填充空隙
计算内容总高度和TableView高度的差值,把这个差值作为底部footer的高度,就能把最后一行“顶”到TableView底部。示例代码如下:override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // 计算内容区总高度 let contentHeight = tableView.contentSize.height // 获取TableView的可用高度(扣除上下内边距) let tableViewAvailableHeight = tableView.bounds.height - tableView.contentInset.top - tableView.contentInset.bottom if contentHeight < tableViewAvailableHeight { // 计算需要填充的空白高度 let footerHeight = tableViewAvailableHeight - contentHeight let footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: footerHeight)) tableView.tableFooterView = footerView } else { // 内容足够时,设置footer高度为0 tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 0)) } }要把这段代码放在
viewDidLayoutSubviews里哦,因为TableView的尺寸可能会随屏幕旋转、布局变化而改变。方法二:AutoLayout约束(更优雅)
如果你的TableView是用AutoLayout布局的,可以给TableView的contentView添加底部约束,但方法一已经足够简单好用,日常开发用得更多~
你当前的代码只是在最后一行显示时自动滚到底部,但并没有限制用户手动下拉的操作。要彻底禁止超出内容底部的滚动,推荐通过监听滚动事件来拦截,给你一个靠谱的实现:
方案:重写scrollViewDidScroll限制滚动范围
在你的TableView所在的ViewController(或者自定义TableView的delegate)里实现UIScrollViewDelegate的scrollViewDidScroll方法,当滚动位置超过内容底部时,强制拉回到底部位置:
func scrollViewDidScroll(_ scrollView: UIScrollView) { // 计算内容区域的底部Y坐标 let contentBottom = scrollView.contentSize.height + scrollView.contentInset.bottom // 计算当前滚动视图的底部Y坐标 let scrollViewBottom = scrollView.bounds.height + scrollView.contentOffset.y // 如果滚动超出了内容底部,强制重置滚动位置 if scrollViewBottom > contentBottom { scrollView.setContentOffset(CGPoint(x: 0, y: contentBottom - scrollView.bounds.height), animated: false) } }
别忘了把ViewController设置为TableView的delegate哦~
另外,如果想要直接关闭整个TableView的弹性滚动(包括顶部下拉的弹性效果),可以直接设置tableView.bounces = false,但这样会同时禁用顶部和底部的弹性,如果你只需要禁止底部过度滚动,上面的方法更精准。
内容的提问来源于stack exchange,提问作者user8893378

