簡體   English   中英

SwiftUI ScrollView 不顯示從 ObservableObject 獲取的結果

[英]SwiftUI ScrollView doesn't show fetched results from an ObservableObject

我試圖通過單擊“獲取”按鈕從 api 獲取數據,並通過 ScrollView 中的 ForEach 循環顯示它們。

我正在使用 MVVM 模型。 獲取本身發生在 ObservableObject 類中。

不幸的是 ScrollView 不顯示內容。 如果我使用的是 List 而不是 ScrollView 它可以正常工作。

你知道我在這里缺少什么嗎?

非常感謝您的幫助!

import SwiftUI

struct Photo: Identifiable, Decodable {

    let id = UUID()
    let title: String
}

class ContentViewModel: ObservableObject {

    let api = "https://jsonplaceholder.typicode.com/photos"

    @Published var photos: [Photo] = []

    func fetchData() {
        print("Fetching started")
        guard let url = URL(string: api) else { return }

        URLSession.shared.dataTask(with: url) { data, _, _ in
            DispatchQueue.main.async {
                self.photos = try! JSONDecoder().decode([Photo].self, from: data!)
                print("Fetching successfull. Fetched \(self.photos.count) photos.")
            }
        }.resume()
    }
}

struct ContentView: View {

    @ObservedObject var contentVM = ContentViewModel()

    var body: some View {
        NavigationView {
            ScrollView {
                ForEach(self.contentVM.photos) { photo in
                    Text(photo.title)
                }
            }
            .navigationBarTitle("Home")
            .navigationBarItems(trailing: Button(action: {

                self.contentVM.fetchData()

                }, label: {
                    Text("Fetch")
            }))
        }
    }
}

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

你沒有錯過任何東西,我認為問題在於渲染內容。 即使在您的示例中,數據顯示在真實設備(iPhone 7 iOS 13.1.1)上,但延遲很長。 嘗試使用較少的內容或幫助ScrollView對齊。 我試過這個 - 在設備上工作得更快,但只在設備上:

class ContentViewModel: ObservableObject {

    let api = "https://jsonplaceholder.typicode.com/photos"

    @Published var photos: [Photo] = []
    @Published var first100Photos: [Photo] = []

    func fetchData() {
        print("Fetching started")
        guard let url = URL(string: api) else { return }

        URLSession.shared.dataTask(with: url) { data, _, _ in
            DispatchQueue.main.async {
                self.photos = try! JSONDecoder().decode([Photo].self, from: data!)
                for index in 0...100 {
                    self.first100Photos.append(self.photos[index])
                }
                print("Fetching successfull. Fetched \(self.photos.count) photos.")
            }
        }.resume()
    }
}

struct ContentView: View {

    @ObservedObject var contentVM = ContentViewModel()

    var body: some View {
        NavigationView {
            ScrollView(.vertical) {
                VStack {
                    ForEach(self.contentVM.first100Photos) { photo in
                        Text(photo.title)
                    }
                }

            }
            .navigationBarTitle("Home")
            .navigationBarItems(trailing: Button(action: {

                self.contentVM.fetchData()

                }, label: {
                    Text("Fetch")
            }))
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM