Images with List and Foreach in SwiftUI

Viewed 1705

Wonder if anyone can help, I'm new to swiftUI and I have been learning over the past couple of weeks. I was having an issue with loading images from a url and displaying them. After successfully figuring this out i have either come across a bug or im doing something really wrong. If i list the images in a foreach loop and build it only half the images appear and if i use just a List they all appear fine which makes no sense to me. If i then add a frame to the image and then set them to lets say 70 x 70 they all display.

class ImageLoader: ObservableObject {
    var didChange = PassthroughSubject<Data, Never>()
    var data = Data() {
        didSet {
            didChange.send(data)
        }
    }

    init(imageUrl:String) {
        guard let url = URL(string: imageUrl) else { return }
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else { return }
            DispatchQueue.main.async {
                self.data = data
            }
        }
        task.resume()
    }
}


struct ImageViewWidget: View {
    @ObservedObject var imageLoader:ImageLoader
    @State var image:UIImage = UIImage()

    init(imageUrl:String) {
        imageLoader = ImageLoader(imageUrl:imageUrl)
    }

    var body: some View {
        
        Image(uiImage: image).resizable()
                .onReceive(imageLoader.didChange) { data in
                    self.image = UIImage(data: data) ?? UIImage()
        }
    }
}

The Above snippet is what is fetching my image from the url

    ForEach(
         networkManager.post,id:\.id){ post in
         AboutRowView(post:post)
    }

Then Looping through returned images and calling my custom row above doesnt work and below does show all images but i dont understand why

    List(
         networkManager.post,id:\.id){ post in
         AboutRowView(post:post)
    }

About row View so u can see whats being called

struct AboutRowView: View {
    let post : Posts
    var body: some View {
        VStack(alignment: .leading, spacing: 8){
            ImageViewWidget(imageUrl: post.featured_image)
            .scaledToFill()
            .frame(height:150)
            .clipped()
            Text(post.title.rendered).lineLimit(nil).padding(.leading,16)
                 HStack{
                      ImageViewWidget(imageUrl: post.featured_image).frame(width:70, height:70)
                     .clipped()
                     .clipShape(Circle())
                     VStack(alignment: .leading, spacing: 4){
                          Text("Test Name").font(.headline)
                          Text("Posted 8 Hours Ago").font(.subheadline)
                     }.padding(.leading, 8)

                 }.padding(.leading, 16).padding(.top, 16)

        }.padding(.leading, -18)

    }
}

0 Answers
Related