Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI List with selector: selecting does not work for custom type (macOS)

I cannot figure out what I am doing wrong here; basically I fail to get a selection in a list of a custom type in my macOS app. Is there a conformance I am missing?

List1 represents a list of my custom type, in which I cannot select an entry, whereas in List2, where I am just using Int, it works.

enter image description here

These are my views:

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)
    }
}

And here's the custom type:

struct Item: Identifiable, Hashable {
    let id: UUID
    let message: String
    
    init(id: UUID = UUID(), message: String) {
        self.id = id
        self.message = message
    }
}
like image 503
appfrosch Avatar asked Oct 19 '25 14:10

appfrosch


1 Answers

Add id

List(localSyslogEntries, id: \.self, selection: $selection) { entry in
like image 166
Raja Kishan Avatar answered Oct 22 '25 10:10

Raja Kishan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!