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

SwiftUI中修改lottieName状态后LottieView不更新动画的问题

解决SwiftUI中LottieView不随状态更新的问题

问题根源在于官方LottieView初始化加载动画后,不会自动监听animation参数的变化,所以即使你更新了lottieName,视图也不会重新加载新动画。下面是两种可行的解决方法:

方法一:使用id修饰符强制重建视图

这是最简单的方案,给LottieView添加.id(lottieName)修饰符。当lottieName变化时,SwiftUI会判定这个视图是新的实例,从而销毁旧视图并创建新的,自动加载新的Lottie动画。

修改后的核心代码:

LottieView(animation: .named(lottieName))
    .aspectRatio(contentMode: .fill)
    .ignoresSafeArea()
    .containerRelativeFrame([.vertical])
    .id(lottieName) // 新增此行,绑定动画名称作为唯一标识

方法二:自定义可动态更新的LottieView

如果你不想每次切换动画都重建视图,可以自定义一个视图,通过监听动画名称的变化手动刷新动画内容:

struct UpdatableLottieView: View {
    var animationName: String
    
    var body: some View {
        LottieView(animation: .named(animationName))
            .onChange(of: animationName) { newName in
                guard let animation = LottieAnimation.named(newName) else { return }
                lottieView?.animation = animation
                lottieView?.play(fromProgress: 0, loopMode: .loop)
            }
            .background(LottieViewObserver(lottieView: $lottieView))
    }
    
    @State private var lottieView: LottieAnimationView?
    
    private struct LottieViewObserver: UIViewRepresentable {
        @Binding var lottieView: LottieAnimationView?
        
        func makeUIView(context: Context) -> UIView { UIView() }
        
        func updateUIView(_ uiView: UIView, context: Context) {
            lottieView = uiView.subviews.first(where: { $0 is LottieAnimationView }) as? LottieAnimationView
        }
    }
}

然后在你的VerseView中替换原LottieView为这个自定义视图:

UpdatableLottieView(animationName: lottieName)
    .aspectRatio(contentMode: .fill)
    .ignoresSafeArea()
    .containerRelativeFrame([.vertical])

两种方法对比:方法一简单直接,适合大多数场景;方法二更灵活,能保留视图的状态(比如播放进度),适合有特殊需求的场景。

内容的提问来源于stack exchange,提问作者Jaseel.Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 21:55:03