【问题标题】:SwiftUI List with selector: selecting does not work for custom type (macOS)带有选择器的 SwiftUI 列表:选择不适用于自定义类型(macOS)
【发布时间】:2021-01-21 08:40:24
【问题描述】:

我无法弄清楚我在这里做错了什么;基本上,我无法在我的 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)
    }
}

这是自定义类型:

struct Item: Identifiable, Hashable {
    let id: UUID
    let message: String
    
    init(id: UUID = UUID(), message: String) {
        self.id = id
        self.message = message
    }
}

【问题讨论】:

    标签: macos swiftui swiftui-list


    【解决方案1】:

    添加标识

    List(localSyslogEntries, id: \.self, selection: $selection) { entry in
    

    【讨论】:

    • 确认工作,谢谢。这是为什么?我符合Identifiable,这还不够吗?
    • 既然你已经在列表中添加了 id 但是列表怎么知道呢?如何识别?这就是为什么需要使用列表中的 id。
    • 嗯,到目前为止,我的印象是符合Identifiable(即肯定有一个唯一的id)足以显示列表行——它就是这样。所以必须有一个原因为什么它不是列表 selection (我也意识到我必须使用id: \.self而不是id: \.id,当它出现时我必须这样做说到行内容。所以我不完全明白,我不得不承认——但话又说回来:它确实有效,所以我相信有一个简单的解释,我只是还不明白,我猜......
    • 需要显式的id,Xcode 13
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2016-05-05
    • 2014-09-08
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多