【问题标题】:SwiftUI - ForEach - Type '_' has no member 'name'SwiftUI - ForEach - 类型“_”没有成员“名称”
【发布时间】:2020-05-31 17:04:46
【问题描述】:

我正在尝试 ForEach 在类内部的字符串数组上并收到错误: Type '_' has no member 'name'

我正在尝试模拟我在本教程中阅读的内容,但不明白为什么我的编译失败。 https://www.hackingwithswift.com/books/ios-swiftui/working-with-identifiable-items-in-swiftui

struct StatisticItem: Codable {
    let name: String
    let startValue: Int
    let modifier: Int
}

class Statistics: ObservableObject {
    let statisticsNames = ["One", "Two"]
    @Published var statList: [StatisticItem]

    init() {
        self.statList = [];
        for statisticsName in statisticsNames {
            self.statList.append(StatisticItem(name: statisticsName, startValue:  Int.random(in: 20 ... 100), modifier: 0))
        }
    }
}

struct ContentView: View {
    @ObservedObject var statistics = Statistics()

    var body: some View {
        Form {
            List {
                // Error shows up on this line: Type '_' has no member 'name'
                ForEach(statistics.statList, id:\.name) { stat in
                    TextField(stat.name)
                }
            }
        }
    }
}

【问题讨论】:

  • 我认为问题不是因为ForEach,而是因为TextField,试着换个简单的Text看看会发生什么

标签: foreach swiftui


【解决方案1】:

首先你的模型需要是可修改的(所以使用var而不是let

struct StatisticItem: Codable {
    var name: String
    var startValue: Int
    var modifier: Int
}

第二,TextField 需要Binding,所以应该如下所示

ForEach(Array(statistics.statList.enumerated()), id:\.1.name) { (i, stat) in
    TextField("", text: self.$statistics.statList[i].name)
}

【讨论】:

  • 你知道为什么我的代码一定和教程不同吗? hackingwithswift.com/books/ios-swiftui/…教程中的struct ExpenseItem使用let教程中的ForEach使用:ForEach(expenses.items, id: \.name) { item in
  • @JordanReed,他们使用Text 的只读(或仅查看,如果您愿意)演示,但您打算修改模型,这是不同的事情。
  • 哈!谢谢!我的意思是使用文本(不是文本字段)。因此,只需将其更改为 Text 也可以解决我的问题。如果我想改变它,你的其他解决方案很高兴。
猜你喜欢
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多