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

如何获取UITableView指定section的全部IndexPath以仅刷新行而非整个section

只刷新UITableView指定Section的所有行(不包含表头表尾)

这个场景我之前做列表排序后也碰到过,reloadSections确实会把整个section的表头、表尾和所有行都重新加载,完全不符合咱们只想刷新行的需求。其实解决思路很简单——先拿到目标section下所有行的IndexPath数组,再用reloadRows方法就行,具体步骤如下:

1. 获取目标Section的总行数

首先通过UITableView的numberOfRows(inSection:)方法,拿到你要刷新的section对应的行数:

let targetSection = 0 // 替换成你实际要刷新的section索引
let rowCount = tableView.numberOfRows(inSection: targetSection)

2. 生成所有行的IndexPath数组

用循环或者Swift的map方法,快速生成该section下每一行对应的IndexPath:

写法一(循环方式):

var indexPaths = [IndexPath]()
for row in 0..<rowCount {
    indexPaths.append(IndexPath(row: row, section: targetSection))
}

写法二(简洁的Swift链式调用):

let indexPaths = (0..<rowCount).map { IndexPath(row: $0, section: targetSection) }

3. 调用reloadRows刷新指定行

最后把生成的indexPaths数组传给reloadRows方法,选择你需要的动画(如果不需要动画就传.none):

// 注意:UI操作必须在主线程执行
DispatchQueue.main.async {
    self.tableView.reloadRows(at: indexPaths, with: .none)
}

额外注意事项

  • 调用前要确保你的数据源已经完成排序更新,不然numberOfRows(inSection:)拿到的行数会和实际不符,导致崩溃。
  • 一定要在主线程执行UITableView的刷新操作,避免UI异常。

内容的提问来源于stack exchange,提问作者LF-DevJourney

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 03:55:56