ios - SwiftUI ScrollView 不显示从 ObservableObject 获取的结果

标签 ios swift scrollview swiftui

我试图通过单击“获取”按钮从 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")
            }))
        }
    }
}

关于ios - SwiftUI ScrollView 不显示从 ObservableObject 获取的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59007442/

相关文章:

iphone - 用于接近检测 iOS 的蓝牙 LE RSSI

ios - 延迟任务直到完成

ios - 在 Swift 中将 .plist 数据读入字典

Android:LinearLayout.addview 动画后向下滚动

android - ScrollView 内具有可扩展 textView 的垂直居中 ConstraintLayout (滚动/居中问题)

ios - UiTabController 应用程序设置

ios - NSMutableURLRequest 不改变 HTTPMethod

swift - AVPlayerViewController 在展开后不会释放

ios - Swift - 数组索引超出范围

ios - 多个 ScrollView 彼此内部