带有选择器的 SwiftUI 列表:选择不适用于自定义类型 (macOS)

app*_*sch 4 macos swiftui swiftui-list

我不知道我在这里做错了什么;基本上,我无法在 macOS 应用程序的自定义类型列表中进行选择。我是否缺少一致性?

List1代表我的自定义类型的列表,在其中我无法选择条目,而在 中List2,我只使用 Int,它可以工作。

在此输入图像描述

以下是我的观点:

struct ContentView: View {
    var body: some View {
        VStack {
            ListView1()
            Divider()
            ListView2()
        }
    }
}

struct ListView1: View {
    @State private var selection: Item? = nil
    
    var localSyslogEntries = [
        Item(message: "message 1"),
        Item(message: "message 2"),
        Item(message: "message 3"),
    ]
    
    var body: some View {
        List(localSyslogEntries, selection: $selection) { entry in
            VStack {
                Text(entry.id.uuidString)
                Divider()
            }
        }
        .frame(minHeight: 200.0)
    }
}

struct ListView2: View {
    @State private var selection: Int? = nil

    var body: some View {
        List(0..<10, id: \.self, selection: $selection) { index in
            VStack {
                Text("Index \(index)")
                Divider()
            }
        }
        .frame(minHeight: 200.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是自定义类型:

struct Item: Identifiable, Hashable {
    let id: UUID
    let message: String
    
    init(id: UUID = UUID(), message: String) {
        self.id = id
        self.message = message
    }
}
Run Code Online (Sandbox Code Playgroud)

Raj*_*han 9

添加 ID

List(localSyslogEntries, id: \.self, selection: $selection) { entry in
Run Code Online (Sandbox Code Playgroud)

  • 好吧,到目前为止,我的印象是,符合“可识别”(即肯定有一个唯一的“id”)足以显示列表行——事实确实如此。因此,当涉及到列表*选择*时,一定有一个原因(我也意识到我必须使用“id:\ .self”而不是“id:\ .id”,我必须使用“id:\ .id”)当谈到行内容时,我不能完全理解它,我必须承认 - 但话又说回来:它确实有效,所以我确信有一个简单的解释,我只是还不明白,我想... (3认同)
  • 需要显式的“id”,Xcode 13 (3认同)