【问题标题】:SwiftUI build a list using enumsSwiftUI 使用枚举构建列表
【发布时间】:2020-07-25 23:25:21
【问题描述】:

我正在尝试基于枚举字符串创建 SwiftUI 列表。我遇到了这个错误:

Cannot invoke initializer for type 'List<_, _>' with an argument list of type '([HomeView.Data], @escaping (String) -> HomeMenuRow)'

我不明白如何使用 id 或如何遍历枚举来构建一行。

【问题讨论】:

  • 你能作为文本发布代码吗?
  • 从技术上讲,您的代码在 Xcode 11.4 中适用于我。分享您的非工作代码以确定确切的问题。
  • 是的,看起来它现在可以工作了。但现在我卡在 switch 语句上取决于是这个 .firsCase 还是另一个我想在这里使用不同的目的地 NavigationLink(destination: LandmarkDetail()) 但这是另一个问题。感谢@staticVoidMan 的帮助

标签: swift swiftui swift5


【解决方案1】:

试试这个:

enum Whatever  : String, CaseIterable, Identifiable {

    var id : String { UUID().uuidString }

    case one = "one"
    case two = "two"
}

struct ContentView: View {
    var body: some View {
        VStack {
            List (Whatever.allCases) { value in
                Text(value.rawValue)
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

【讨论】:

  • 谢谢,很奇怪,我只是将 .rawValue 添加到我的示例中,它也可以工作。
  • 在 Xcode 12 上,这让我崩溃了。我将var id 改为返回self.rawValue,这为我解决了这个问题。
  • 枚举代码有一个副作用:检索Whateverid 将始终生成一个新的UUID,因为在getter 中调用了UUID()。这可能会在使用时导致无限循环,例如在ForEach(Whatever.allCases) { ... }
  • 这个答案包含一个强烈的问题,即Not Stable identifier。查看this answer 以查看How to confirm an enumeration to Identifiable protocol in Swift?
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多