You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift:实现UITableView分区行数限制及滚动到底部动态扩展行数

UITableView本地数据分段平滑扩展显示解决方案

1. 定义跟踪变量

在你的视图控制器中添加两个变量,用来控制当前显示的最大行数和每次扩展的步长:

private var currentDisplayLimit = 100 // 初始只显示100行
private let loadStep = 100 // 每次滚动到底部扩展100行

2. 更新行数计算逻辑

替换原来硬编码100的实现,用currentDisplayLimit来动态控制显示行数,同时确保不会超过实际数据总量:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let totalCount = delegate.groupedSessions[section].count
    return min(currentDisplayLimit, totalCount)
}

3. 监听滚动并触发扩展

实现UIScrollViewDelegate的滚动监听方法,判断用户滚动到底部时,扩展显示上限并平滑插入新行:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    // 计算滚动位置,判断是否到达底部(加20pt容错,避免误触发)
    let bottomOffset = scrollView.contentSize.height - scrollView.frame.height
    if scrollView.contentOffset.y >= bottomOffset - 20 {
        // 遍历所有section处理(如果是单section可简化)
        for section in 0..<delegate.groupedSessions.count {
            let totalCount = delegate.groupedSessions[section].count
            guard currentDisplayLimit < totalCount else { continue }
            
            let oldLimit = currentDisplayLimit
            currentDisplayLimit = min(currentDisplayLimit + loadStep, totalCount)
            
            // 生成需要插入的行的IndexPath
            var insertIndexPaths = [IndexPath]()
            for row in oldLimit..<currentDisplayLimit {
                insertIndexPaths.append(IndexPath(row: row, section: section))
            }
            
            // 批量插入,实现平滑过渡
            tableView.performBatchUpdates({
                tableView.insertRows(at: insertIndexPaths, with: .automatic)
            }, completion: nil)
        }
    }
}

关键说明

  • 确保视图控制器已设置tableView.delegate = self,否则滚动监听不会生效
  • 容错偏移量20可根据需求调整,避免用户未完全滚动到底部就触发扩展
  • 多section场景下,代码已经做了遍历处理,单section可去掉外层循环简化逻辑
  • 使用performBatchUpdates插入行而非reloadData,能保证平滑的动画效果

内容的提问来源于stack exchange,提问作者adalovelacy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 20:01:33