Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI ForEach views not updating for the first time

I'm trying to populate a group of views using ForEach. I've used Alamofire for fetching the data and setting the @State property to trigger an update. Unfortunately, the updates only show up when I switch screens(Using a TabBar) or go to the home screen and re-open the app.

Following is the code snippet that I've used:

@State var posts : [Post]
    
    var body: some View {
        ScrollView{
            VStack(alignment: .leading, spacing: 0){
                ForEach(posts, id: \.id) { preview in
                    PreviewDetailView(preview: preview).background(Color(.white).cornerRadius(30))
                }
            }
        }.onAppear(perform: {fetchPosts()})
    }

Apparently, the PreviewDetailView(in which I'm displaying the API response data) gets triggered but the view doesn't update.

like image 952
AnupamChugh Avatar asked Nov 26 '19 16:11

AnupamChugh


1 Answers

The reason is when you use stack or ForEach within ScrollView, you have to setFrame limits to initialize the view Setting like the following.

ScrollView{
    VStack(alignment: .leading, spacing: 0){        
        ForEach(self.posts, id: \.id) { preview in
           PreviewDetailView(preview: preview)
               .background(Color(.red).cornerRadius(30))
        }.frame(maxWidth: .infinity) // Here
    }
}.onAppear{
    self.fetchPosts()   
}
like image 61
E.Coms Avatar answered Oct 07 '22 01:10

E.Coms