使用Lottie API在静态TableView Cell中调用AnimationView不显示问题求助
解决TableView Cell中Lottie AnimationView不显示的问题
我来帮你排查一下这个问题,你的代码里有几个容易踩的细节坑,咱们一步步梳理修正:
核心问题分析
首先看你代码里的一个关键错误:你创建了局部变量let animationView = LOTAnimationView(name: "loader1"),但后续所有操作的都是self.animationView——这就导致你实际初始化的动画视图根本没被添加到cell上,反而操作的是未正确初始化的类实例属性(如果self.animationView之前没赋值的话,它就是nil),自然看不到动画。
另外,你获取cell位置和大小的方式也有问题:tableView.cellForRow(at: index)返回的cell的center是相对于tableView的坐标系,而你把动画视图的center设成这个值,会导致动画视图在cell内部的位置完全错误。
修正后的代码
先给你一个能正常运行的版本,我会逐行解释:
// 1. 安全获取目标cell,避免强制解包崩溃,同时排查cell是否在屏幕可见范围内 guard let targetCell = self.tableView.cellForRow(at: IndexPath(row: 9, section: 0)) else { print("目标cell不可见或不存在") return } // 2. 创建动画视图,直接使用局部变量,避免和类属性混淆 let animationView = LOTAnimationView(name: "loader1") // 3. 基于cell自身的bounds设置动画视图的位置和大小(bounds是cell内部的坐标系,比frame更可靠) let animationWidth = targetCell.bounds.width / 2 let animationHeight: CGFloat = 50 // 让动画视图在cell内居中显示 animationView.frame = CGRect( x: (targetCell.bounds.width - animationWidth) / 2, y: (targetCell.bounds.height - animationHeight) / 2, width: animationWidth, height: animationHeight ) // 4. 配置动画属性 animationView.contentMode = .scaleAspectFill animationView.loopAnimation = true // 5. 先移除cell内可能存在的旧动画视图(避免重复添加导致异常) targetCell.subviews.filter { $0 is LOTAnimationView }.forEach { $0.removeFromSuperview() } // 6. 添加并播放动画 targetCell.addSubview(animationView) animationView.play()
额外优化建议
如果你的cell是自定义TableViewCell,建议把动画相关逻辑封装到cell内部,这样代码耦合度更低,也更容易维护:
自定义Cell示例
class CustomAnimationCell: UITableViewCell { // 保存动画视图的引用,方便后续停止或移除 private var animationView: LOTAnimationView? /// 显示加载动画 func showLoadingAnimation() { // 先清理旧动画 hideLoadingAnimation() let newAnimationView = LOTAnimationView(name: "loader1") let animationWidth = bounds.width / 2 let animationHeight: CGFloat = 50 newAnimationView.frame = CGRect( x: (bounds.width - animationWidth) / 2, y: (bounds.height - animationHeight) / 2, width: animationWidth, height: animationHeight ) newAnimationView.contentMode = .scaleAspectFill newAnimationView.loopAnimation = true addSubview(newAnimationView) newAnimationView.play() animationView = newAnimationView } /// 隐藏加载动画 func hideLoadingAnimation() { animationView?.stop() animationView?.removeFromSuperview() animationView = nil } }
ViewController中调用
guard let animationCell = tableView.cellForRow(at: IndexPath(row: 9, section: 0)) as? CustomAnimationCell else { print("无法获取目标自定义cell") return } animationCell.showLoadingAnimation()
最后排查点
如果还是看不到动画,检查这两个地方:
- 确认cell的
clipsToBounds属性不是true,如果开启了裁剪,动画视图超出cell范围的部分会被隐藏 - 确保你的Lottie文件路径正确(你说已经排除了这个问题,但可以再确认下文件是否被正确加入项目的Copy Bundle Resources中)
内容的提问来源于stack exchange,提问作者Annabelle Sykes
相关产品推荐
相关产品推荐

