ScrollView not updated

ScrollView does not update after loading data. ScrollView successfully displays data only after I switch to another screen and come back. https://youtu.be/0q3R6LaKbnE

For asynchronous image loading, use: https://github.com/dmytro-anokhin/url-image

import Combine
import SwiftUI

class NewsAPI: ObservableObject {

    @Published var articles: Articles = [Article]()

    init() {
        guard let url: URL = URL(string: "https://newsapi.org/v2/top-headlines?country=ru&apiKey=376a97643c6c4633afe57427b71e8ebd") else { return }
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                guard let json = data else { return }
                let welcome = try JSONDecoder().decode(ModelNews.self, from: json)
                DispatchQueue.main.async {
                    self.articles = welcome.articles!
                }
            }
            catch {
                print(error)
            }
        }
        .resume()
    }
}

struct CardList: View {

    @ObservedObject var newsAPI: NewsAPI = NewsAPI()

    var body: some View {
        NavigationView {
            ScrollView {
                VStack(alignment: .center) {
                    ForEach(self.newsAPI.articles, id: \.self) { i in
                        CardView(article: i)

Upvotes: 2

Views: 750

Answers (2)

ninjahamster
ninjahamster

Reputation: 146

I solved the problem. The updating works fine, the problem is something else! I've struggled for hours to solve this and I've found a solution.

If you provide default values from the same type or a view, which is only shown, when the array is empty, everything is working as it should. Seems like the view have the wrong size, if the array is empty, so you don't see anything, because the size isn't changing with the update of the content.

In short words: Provide a default value or an alternative view, which is shown, if the array is empty.

Hope that helps!

Upvotes: 7

user12132829
user12132829

Reputation:

You could test it without the dispatchqueue. I had a similar issue on a list and got it to work when i removed the Dispatchqueue.

Just self.articles = welcome.articles!.

Upvotes: 0

Related Questions