Home > other >  SwiftUI how to lazy load a stack and async changing their value
SwiftUI how to lazy load a stack and async changing their value

Time:10-31

I want to use lazyStack to load my data and use DispatchQueue to update its value after a specific time. But the view doesn't change and I don't know how to refresh the value in the view

import SwiftUI
 struct CustomImages{
     var image:Image
     var id = 0
    init(){
        print("loading")
        self.image = Image("UnknownAlbum")
        self.id = 1
    }
}
struct SwiftUIView: View {
    var body: some View {
        VStack{
            ScrollView {
                LazyVStack {
                    ForEach(0..<100){row in
                        var i = CustomImages()
                        HStack{
                            i.image
                            Text("\(i.id)")
                            .onAppear{
                                DispatchQueue.main.asyncAfter(deadline: .now()){
                                    print("adding")
                                    i.id  = 2
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

CodePudding user response:

Variables in Custom Images should be linked through @Binding. In SwiftUI, a typical declaration cannot detect variation. I've used the example code, and I think you can change it according to your purpose.

In the example code, the logic changes to the second image after 3 seconds.

import SwiftUI

struct ContentView: View {
    
    @State private var image = Image("farnsworth")
    
    var body: some View {

        ScrollView {
            LazyVStack {
                ForEach(0..<30) { row in
                    
                    let id = Binding<Int>(get: { row }, set: {_ in})
                    
                    let customImages = CustomImages(image: $image, id: id)
                    
                    HStack {
                        customImages.image
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                        Text("\(customImages.id)")
                    }
                    .padding()
                    .onAppear {
                        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()   3) {
                            image = Image("farnsworth2")
                        }
                    }
                }
            }
        }
    }
}

 struct CustomImages{
     @Binding var image: Image
     @Binding var id: Int
}


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