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

Swift中如何让UITableView滚动时UIActivityIndicatorView同步滚动?

解决UITableViewController中UIActivityIndicatorView不随滚动移动的问题

这个问题我之前也碰到过,核心是对UITableView的层级和滚动逻辑理解有点偏差,我来给你一步步拆解并解决:

问题原因

你现在把UIActivityIndicatorView添加到了UITableViewController的view(也就是UITableView本身)上,并且将它的位置设置为self.view.center——这个位置是相对于tableView的屏幕显示frame的中心,而不是它的可滚动内容区域的中心。

当你滚动tableView时,只有内部的内容区域(包含cell的部分)会移动,而指示器因为绑定在tableView的固定frame上,会一直停留在屏幕中间,不会跟着内容滚动。

解决方案

方法一:让指示器随tableView内容滚动(绑定到内容区域)

如果你希望指示器跟着tableView的内容一起滚动(比如显示在列表中间,随用户滚动上下移动),可以这样修改代码:

// 创建并配置指示器
indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
indicator.hidesWhenStopped = true
indicator.style = .white
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.6)
indicator.layer.cornerRadius = 15

// 计算内容区域的中心位置:如果内容高度小于屏幕高度,就居中在屏幕;否则居中在内容区域
let contentCenterX = tableView.contentSize.width / 2
let contentCenterY = max(tableView.contentSize.height / 2, tableView.bounds.height / 2)
indicator.center = CGPoint(x: contentCenterX, y: contentCenterY)

// 添加到tableView上,此时它属于可滚动内容的一部分
tableView.addSubview(indicator)
indicator.startAnimating()

方法二:将指示器作为tableHeaderView(固定在列表顶部)

如果你的需求是让指示器显示在列表顶部,随滚动一起移动,可以把它设置为tableView的表头:

// 创建并配置指示器
indicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
indicator.hidesWhenStopped = true
indicator.style = .white
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.6)
indicator.layer.cornerRadius = 15

// 创建容器view作为表头,避免指示器的大小直接限制表头高度
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 100))
indicator.center = CGPoint(x: headerView.bounds.width / 2, y: headerView.bounds.height / 2)
headerView.addSubview(indicator)

// 设置为tableView的表头
tableView.tableHeaderView = headerView

indicator.startAnimating()

额外提示

  • 如果你的tableView还在加载数据(此时contentSize可能为(0,0)),可以先把指示器放在屏幕中心,等数据加载完成后再调整它的位置到内容区域中心。
  • 记得在不需要指示器时调用indicator.stopAnimating(),如果不再需要可以调用indicator.removeFromSuperview()释放资源。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:24:22