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

iOS开发:如何为点击屏幕新增的TableView的storyIndexRow行添加动画?

给TableView新增行添加动画效果的实现方案

你的现有代码仅完成了数据源更新,但未通知TableView以动画方式插入新行。要实现目标,需使用UITableView的insertRows(at:with:)方法,而非直接调用reloadData(后者不会触发插入动画)。

修改后的完整代码

view.tapHandle {
    if self.storyIndexRow < self.storyContents.count {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            // 确定要插入的行的位置(当前storyIndexRow就是新行要插入的索引)
            let insertIndexPath = IndexPath(row: self.storyIndexRow, section: 0)
            
            // 更新数据源
            self.messageArr.append(self.storyContents[self.storyIndexRow])
            self.storyIndexRow += 1
            
            // 以动画方式插入新行
            self.tableView.insertRows(at: [insertIndexPath], with: .automatic)
        }
    }
}

关键说明

  • 动画类型可选:with参数可替换为需要的动画效果,比如.fade(淡入)、.right(从右侧滑入)、.left(从左侧滑入)等,.automatic会根据系统设置自动选择合适动画。
  • 主线程操作要求:UI更新必须在主线程执行,这里已通过DispatchQueue.main.asyncAfter保证。
  • 数据源与UI同步:必须先更新数据源(messageArr),再调用insertRows方法,否则会触发UITableView数据源不一致的崩溃。
  • 多Section适配:如果TableView有多个section,需将section: 0替换为对应section的索引。

内容的提问来源于stack exchange,提问作者Nhân Hồ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:24:51