api请求中的对象在ForEach中打印,但不在列表中

时间:2019-11-05 03:48:17

标签: swift swiftui

我正在尝试创建从API请求中接收到的对象列表。该对象是可识别的。奇怪的是,当我在ForEach循环中遍历对象的titles参数时,它会打印出预期的结果。但是,当我将其更改为列表时,它不会显示任何内容,也不会给出错误或任何其他指示出问题。我想念什么?

这是我的对象:

struct Item: Identifiable, Decodable {
    let id = UUID()
    let title: String?
    let canonicalURL: String?
    let unread: Bool?
    let author: String?

    init(title: String?, canonicalURL: String?, unread: Bool?, author: String?){
        self.title = title
        self.canonicalURL = canonicalURL
        self.unread = true
        self.author = author
    }
}

这是我的观点:

@ObservedObject var articlesVM = ArticlesViewModel()

    var body: some View {
        NavigationView{
            ScrollView{

                ForEach (articlesVM.entries) { entry in
                    Text(entry.title!)
                } //THIS WORKS

                List (articlesVM.entries) { entry in
                    Text(entry.title!)
                } //THIS DOESNT WORK

            }.navigationBarTitle("Articles")
            .navigationBarItems(trailing: Button(action: {
                print("Fetching Data")
                self.articlesVM.fetchArticles()
            }, label: {
                Text("Fetch Articles")
            }))
        }
    }
}

1 个答案:

答案 0 :(得分:2)

列表本身是可滚动的。尝试以下身体:

var body: some View {
    NavigationView{
        List (articlesVM.entries) { entry in
                Text(entry.title!)
        }.navigationBarTitle("Articles")
        .navigationBarItems(trailing: Button(action: {
            print("Fetching Data")
            self.articlesVM.fetchArticles()
        }, label: {
            Text("Fetch Articles")
        }))
    }
}