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

iOS tableView首次加载时实现section与row自定义入场动画如何实现?

iOS UITableView 分区与行入场动画实现方案

基础参数定义

首先提前声明动画控制参数与状态标记,避免动画重复执行:

// 动画配置参数
private let sectionAnimationDuration: TimeInterval = 0.3
private let rowAnimationDuration: TimeInterval = 0.25
private let rowStaggerRatio: Double = 0.5 // 前一个动画执行50%时触发下一个
// 动画执行状态标记,避免滚动/复用时重复触发入场动画
private var hasTriggeredEntranceAnimation = false

Section 入场动画实现

在tableView(_:willDisplayHeaderView:forSection:)代理方法中处理分区视图的左滑入场逻辑:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard section == 0, !hasTriggeredEntranceAnimation else { return }
    // 初始状态:section 向左偏移出屏幕
    view.transform = CGAffineTransform(translationX: -UIScreen.main.bounds.width, y: 0)
    UIView.animate(withDuration: sectionAnimationDuration, delay: 0, options: .curveEaseOut) {
        view.transform = .identity
    } completion: { [weak self] _ in
        guard let self = self else { return }
        // section动画完成后标记,触发row的批量入场动画
        self.hasTriggeredEntranceAnimation = true
        tableView.visibleCells.enumerated().forEach { index, cell in
            // 按索引计算每个row的延迟时间
            let delay = self.rowAnimationDuration * self.rowStaggerRatio * Double(index)
            // 初始状态:cell 向上偏移出自身高度位置
            cell.transform = CGAffineTransform(translationX: 0, y: -cell.bounds.height)
            cell.alpha = 0
            UIView.animate(withDuration: self.rowAnimationDuration, delay: delay, options: .curveEaseOut) {
                cell.transform = .identity
                cell.alpha = 1
            }
        }
    }
}

多Section场景适配调整

如果存在多个Section需要按顺序执行动画,可以调整逻辑如下:

  • 每个Section的入场延迟按索引计算:sectionDelay = sectionAnimationDuration * Double(sectionIndex)
  • 每个Section内部的Row动画逻辑和单Section逻辑一致

注意事项

  • 所有入场动画仅在列表首次加载时触发,滚动复用cell/section时不会重复执行,符合常规交互逻辑
  • 可以根据需求调整动画时长、交错比例参数,匹配需要的动效节奏
  • 若需要在列表刷新后重新触发入场动画,重置hasTriggeredEntranceAnimation为false即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:09:00