SwiftUI Lottie 动画卡在 SrollView LazyHStack 中

问题描述

这是我的代码

import SwiftUI
import Lottie

struct LottieLoadingList: View {
    var body: some View {
        ScrollView(.horizontal,showsIndicators: false,content: {
            LazyHStack{
                ForEach(0..<14) { _ in
                    LottieLoadingView(isloading: true)
                }
            }
        })
        .frame(width: 375,height: 68)
    }
}

struct WrappedLoadingView: View {
    var isloading: Bool = false
    var body: some View {
        vstack {
            LottieLoadingView(isloading: isloading)
            .padding(10)
            .frame(maxWidth: 54,maxHeight: 73)
        }
    }
}

struct LottieLoadingView: UIViewRepresentable {
    typealias UIViewType = UIView
    let lottieFileName: String = "loading"
    let animationView = AnimationView()
    let isloading: Bool
    
    func makeUIView(context: UIViewRepresentableContext<LottieLoadingView>) -> UIView {
        let view = UIView(frame: .zero)
        let animation = Animation.named(lottieFileName)
        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),])
        return view
    }
    
    func updateUIView(_ uiView: UIView,context: UIViewRepresentableContext<LottieLoadingView>) {
        if isloading {
            context.coordinator.parent.animationView.pause()
            context.coordinator.parent.animationView.isHidden = true
        } else {
            context.coordinator.parent.animationView.isHidden = false
            context.coordinator.parent.animationView.play()
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject {
        var parent: LottieLoadingView
        init(_ parent: LottieLoadingView) {
            self.parent = parent
        }
    }
}

运行时 scrollview 滚动非常缓慢,一点也不流畅。

我认为问题可能是代码 init 同时有很多 loadingviews(ForEach)。我想要的就像 UIKit 中的集合一样,cellForItem 函数可以有一个地方可以重用加载 animationview;而且这里的加载状态是由数据的状态控制的,有些可能加载成功所以他们不显示加载,有些可能仍在进行中所以他们需要加载,在我的代码中,我想所有的数据都在进行中,在这种情况下,我如何重用 loadingview 来平滑滚动加载视图?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)