【问题标题】:Getting errors with building a List view in SwiftUI在 SwiftUI 中构建列表视图时出错
【发布时间】:2019-08-24 20:16:53
【问题描述】:

对于我的应用,我正在尝试从一组元组中创建一个列表,但出现以下错误:

无法使用类型为 '([EggDayList.EggDay], @escaping ([CellDayRow.EggDay]) -> NavigationLink) 的参数列表调用类型 'List<_ _>' 的初始化程序。

我之前已经列出了几个列表,但我看不出这里出了什么问题。

struct EggDayList: View {

    typealias EggDay = (day: Int, mW: Double, measured: Bool, daily: Double)
    var actualWeights : [EggDay] = [
        (1, 35.48, true, 0.00), (2, 35.23, true, 0.00), (3, 34.92, true, 0.00), (4, 34.64, true, 0.00),(5, 34.29, true, 0.00), (6, 33.86, true, 0.00), (7, 33.48, true, 0.00), (8, 33.12, true, 0.00), (9, 32.77, true, 0.00), (10, 32.45, true, 0.00), (11, 32.08, true, 0.00), (12, 31.87, true, 0.00), (13, 31.55, true, 0.00), (14, 31.46, true, 0.00), (15, 31.33, true, 0.00), (16, 31.24, true, 0.00), (17, 31.14, true, 0.00), (18, 31.02, true, 0.00), (19, 30.90, true, 0.00), (20, 30.81, true, 0.00), (21, 30.65, true, 0.00), (22, 30.54, true, 0.00), (23, 30.31, true, 0.00), (24, 30.12, true, 0.00), (25, 29.97, true, 0.00), (26, 29.82, true, 0.00) ]

    var body: some View {

        NavigationView {

            List(actualWeights) { eggDay in
                NavigationLink(destination: EggDetail()) {
                    CellDayRow(eggDay: eggDay)
                }
            }
            .navigationBarTitle("Measurements")
        }
    }
}

struct CellDayRow: View {
    typealias EggDay = (day: Int, mW: Double, measured: Bool, daily: Double)
    let eggDay : [EggDay]
    var body: some View {
        HStack {
            Text("String(eggDay.day)")
                .bold()
                .font(.headline)
            }
    }
}

【问题讨论】:

    标签: ios swift list swiftui xcode11


    【解决方案1】:

    该错误是因为actualWeights 不是Identifiable 并且不能单独用作list 参数。您应该为每个元素指定标识符:

    Xcode 11 beta 5 及更高版本:

    List(actualWeights, id: \.day) { eggDay in Text("Text") }
    

    Xcode 11 beta 4 及以下:

    List(actualWeights.identified(by: \.day)) { eggDay in Text("Text") }
    

    但是您应该为每个元素都有一个唯一的 id 并根据它创建列表。像这样:

    typealias EggDay = (id: String, day: Int, mW: Double, measured: Bool, daily: Double)
    let uniqueEggDay = (UUID().uuidString, 1, 35.48, true, 0.00)
    List([uniqueEggDay], id: \.id) { eggDay in Text("Text") }
    

    我会为 EggDay 创建一个 struct 而不是 tuple 并使其符合 Identifiable 协议,如果我在哪里的话。它更方便,更清洁。

    【讨论】:

    • 这是您提到的错误的答案。如果您无法处理其他错误,请随时提出新问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2021-10-28
    相关资源
    最近更新 更多