【问题标题】:When using combine in SwiftUI to update a Lottie Animation, it fails to update at the right time and gives an unexpected result在 SwiftUI 中使用 combine 更新 Lottie Animation 时,它未能在正确的时间更新并给出意外的结果
【发布时间】:2023-10-02 06:19:01
【问题描述】:

我有一个使用 combine 和计时器的 ViewModel,我希望这个 ViewModel 使用新动画更新 LottieView 和文件名。当计时器倒计时时,我希望它发布和发送特定字符串,这些字符串将是 json Lottie 文件名。当我的 ContentView 收到这些文件名时,我希望它动态更新 LottieViews 动画。

所以我在 ContentView 中创建了一个名为 name 的 @State 变量,并使其与传入的接收值相等。但是,让我感到困惑的是,正在发布并在 10 秒时从 ViewModels 计时器发送的文件名假设在 LottieView(filename: name) 中接收和使用标记。

但是,当我启动应用程序时,这个 LottieView 会立即运行这个文件。怎么会这样?文件名存在于整个应用程序中的唯一位置是当计时器达到 10 秒时,它甚至不应该在调用 LottieView(name) 时存在。它还会忽略应该在 19 秒标记处运行的前一个文件名。如果我要一起忽略 LottieView(name) 并运行文本视图,那么在本例中为 Text(name),当我运行应用程序时,文本会在计时器达到 10 时正确更改。

那么 LottieView(name) 怎么会这样运行呢?我验证了这些文件也正确匹配它们的动画。

import SwiftUI
import Combine

class ViewModel: ObservableObject {
    
    var anyCancellable: AnyCancellable?
    let publish = PassthroughSubject<String, Never>()
    
    private var timer: Timer?
    private var scheduleTime = 20
    
    init() {
        fire()
        anyCancellable = publish.sink { str in
            print("Value that is being passed over: \(str)")
        }

    }
    
    func fire() {
        print("Fire timer")
        timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            
            
            self.scheduleTime -= 1
            print(self.scheduleTime)
            if self.scheduleTime == 19 {
                self.publish.send("13865-sign-for-error-flat-style")
            }
            if self.scheduleTime == 10 {
               self.publish.send("4174-unlock-to-premium")
                timer.invalidate()
            }
        }
    }
}


import SwiftUI
import Combine

struct ContentView: View {
    
    @ObservedObject var vm = ViewModel()
    @State var name: String = ""
    var body: some View {
      
        VStack {
            LottieView(filename: $name)
            Text(name)
        }
            .onReceive(vm.publish, perform: { value in
                print("passed over : \(value)")
                name = value
                print(name)
            })
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


import SwiftUI
import Lottie

struct LottieView: UIViewRepresentable {
    
  typealias UIViewType = UIView
  @Binding var filename: String
  
  func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
    let view = UIView(frame: .zero)
    
    let animationView = AnimationView()
    let animation = Animation.named(filename)
    animationView.animation = animation
    animationView.contentMode = .scaleAspectFit
    animationView.play()
    
    animationView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(animationView)
    
    NSLayoutConstraint.activate([
      animationView.widthAnchor.constraint(equalTo: view.widthAnchor),
      animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
      animationView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      animationView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
    ])
    
    return view
  }
  
  func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
  }
    
}

【问题讨论】:

  • 您的问题是关于使用 Lottie?
  • 是的,我认为可能是这样。当@State name 属性被覆盖时,我不明白为什么 LottieView(filename: name) 没有触发新的动画。
  • 但是我最近确实发现,如果我要注释掉整个计时器函数,那么这些文件不会在我的程序中的任何地方调用,动画仍然会运行。这让我相信文件名以某种方式被缓存在 Lottie 依赖项中。所以这是触发第一个动画的修复。如果 name = “” { LottieView(filename: $name) }
  • 我不喜欢洛蒂和那种工作方式!它仍然在 UIKit 上,他们向你收取愚蠢的代码,你不会问他们你的问题吗?我认为至少他们得到了钱,然后他们也应该提供支持,最后我不知道你怎么能相信他们的产品把它放在你的应用程序中,即使它是免费的。
  • 当状态更新时,它调用UIViewRepresentableupdateUIView,在你的情况下它是空的。这就是为什么什么都没有发生。在updateUIView 内部,您需要使用现在的新文件名重置/重新启动动画

标签: swift swiftui combine lottie


【解决方案1】:

经过一天的搜索,没有找到答案,我可能想出了一个不太正确的解决方案,但它似乎有效(保存临时文件名并在更新 LottieView 后检查名称):

import SwiftUI
import Lottie

struct LottieView: UIViewRepresentable {
    
    typealias UIViewType = UIView
    var filename: String
    var animationView = AnimationView()
    let isPaused: Bool
    var needUpdate: Bool = false {
        didSet {
            if needUpdate {
                let animation = Animation.named(filename)
                animationView.animation = animation
                animationView.contentMode = .scaleAspectFit
                animationView.loopMode = .loop
                animationView.play()
                needUpdate = false
            }
        }
    }
    
    func makeUIView(context: UIViewRepresentableContext<LottieView>) -> UIView {
        let view = UIView(frame: .zero)
        
        let animation = Animation.named(filename)
        animationView.animation = animation
        animationView.contentMode = .scaleAspectFit
        animationView.loopMode = .loop
        
        animationView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(animationView)
        
        NSLayoutConstraint.activate([
            animationView.widthAnchor.constraint(equalTo: view.widthAnchor),
            animationView.heightAnchor.constraint(equalTo: view.heightAnchor),
        ])
        animationView.play()
        return view
    }
    
    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<LottieView>) {
        let tempFileName = context.coordinator.parent.filename
        DispatchQueue.main.async {
            context.coordinator.parent.filename = filename
            if tempFileName != filename {
                context.coordinator.parent.needUpdate = true
            }
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject {
        var parent: LottieView
        
        init(_ parent: LottieView) {
            self.parent = parent
        }
    }
}

【讨论】: