【问题标题】:ForEach through Indices SwiftUIForEach 通过索引 SwiftUI
【发布时间】:2020-09-28 21:54:42
【问题描述】:

我正在尝试使用 Contentful CMS 并遍历数据数组,以便可以在水平磁贴中以标题、样式和描述组的形式显示它。我能够使用硬编码的数据数组来做到这一点,但我无法做到这一点......

我已经包含了我的视图、视图模型和模型,你会看到模型持有我的 API 调用,我的视图模型只处理我的可识别数据,然后我的视图处理我的视图本身。

// MARK: - View

struct BeerListView: View {
    @ObservedObject var draftVM = BeerModel()
    
    var body: some View {
        
        
        VStack {
            ForEach(draftVM.draftBeerArray.indices, id: \.self) { item in
                VStack {
                    Text(item.title)
                    Text(item.style)
                    Text(item.description)
                }
            }
        }
    }
}

// MARK: - View Model

struct BeersData: Identifiable {
    var id = UUID()
    var title: String = ""
    var style: String = ""
    var description: String = ""
}

// MARK: - Model

private let client = Client(spaceId: "SPACEID", accessToken: "SUPERSECRETTOKEN")

func getArray(id: String, completion: @escaping ([Entry]) -> ())  {
    let query = Query.where(contentTypeId: id)
    
    client.fetchArray(of: Entry.self, matching: query) { result in
        switch result {
        case .success( let array):
            DispatchQueue.main.async {
              completion(array.items)
                print(result)
            }
        case.failure(let error):
            print(error)
        }
    }
}


class BeerModel: ObservableObject  {
    @Published var draftBeerArray: [BeersData] = beerArray
        
    init() {
        getArray(id: "beers") { (items) in
            items.forEach { (items) in
                self.draftBeerArray.append(BeersData (
                    title: items.fields["title"] as! String,
                    style: items.fields["style"] as! String,
                    description: items.fields["description"] as! String))
            }
        }
    }
}

【问题讨论】:

  • 为什么是索引?如果你迭代索引,你的“项目”是一个 Int。只需直接遍历对象: ForEach(draftVM.draftBeerArray) { item in ...

标签: swiftui contentful mobile-development


【解决方案1】:

如果你通过索引进行迭代,那么你的闭包参数就是索引,所以你必须通过索引访问数组,比如

ForEach(draftVM.draftBeerArray.indices, id: \.self) { index in
    VStack {
        Text(draftVM.draftBeerArray[index].title)

如果您想访问项目,那么您必须按项目进行迭代(它们已经可以识别)

ForEach(draftVM.draftBeerArray, id: \.self) { item in
    VStack {
        Text(item.title)

【讨论】:

    猜你喜欢
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多