首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在UITableView上滚动时UIActivityIndicatorView会消失

基础概念

UITableView 是 iOS 开发中常用的一个控件,用于展示列表数据。UIActivityIndicatorView 是一个用于显示加载状态的控件,通常在数据加载时显示,加载完成后隐藏。

相关优势

  • 用户体验UIActivityIndicatorView 可以提供良好的加载反馈,让用户知道应用正在处理请求。
  • 界面友好:通过显示加载指示器,可以避免用户在数据加载过程中误操作。

类型

UIActivityIndicatorView 有几种样式可供选择:

  • UIActivityIndicatorView.Style.large
  • UIActivityIndicatorView.Style.medium
  • UIActivityIndicatorView.Style.small

应用场景

  • 数据加载:当从网络或本地数据库加载数据时。
  • 文件上传/下载:在文件传输过程中显示加载状态。
  • 复杂计算:在执行耗时的计算任务时。

问题分析

UITableView 上滚动时 UIActivityIndicatorView 消失的问题通常是由于 UITableView 的复用机制导致的。当 UITableView 滚动时,它会复用不再显示的 cell,这可能会导致 UIActivityIndicatorView 被错误地隐藏或移除。

原因

  1. Cell 复用UITableView 会复用 cell,如果复用的 cell 包含 UIActivityIndicatorView,可能会导致其状态不一致。
  2. 布局问题UIActivityIndicatorView 的布局可能没有正确设置,导致在滚动时被错误地隐藏。

解决方法

1. 使用自定义 Cell

创建一个自定义的 cell 类,并在其中管理 UIActivityIndicatorView 的显示和隐藏。

代码语言:txt
复制
class CustomTableViewCell: UITableViewCell {
    let activityIndicator = UIActivityIndicatorView(style: .medium)

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupActivityIndicator()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupActivityIndicator() {
        contentView.addSubview(activityIndicator)
        activityIndicator.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            activityIndicator.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            activityIndicator.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
        ])
    }

    func startAnimating() {
        activityIndicator.startAnimating()
    }

    func stopAnimating() {
        activityIndicator.stopAnimating()
    }
}

UITableViewDataSource 中使用自定义 cell:

代码语言:txt
复制
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomTableViewCell
    if shouldShowActivityIndicator(for: indexPath) {
        cell.startAnimating()
    } else {
        cell.stopAnimating()
    }
    return cell
}

2. 使用 UITableViewcontentOffset 监听

通过监听 UITableViewcontentOffset 变化,手动控制 UIActivityIndicatorView 的显示和隐藏。

代码语言:txt
复制
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let offsetY = scrollView.contentOffset.y
    if offsetY > 0 {
        activityIndicator.isHidden = true
    } else {
        activityIndicator.isHidden = false
    }
}

参考链接

通过以上方法,可以有效解决在 UITableView 上滚动时 UIActivityIndicatorView 消失的问题。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

14分30秒

Percona pt-archiver重构版--大表数据归档工具

3分26秒

企业网站建设的基本流程

领券