List selection not changing value

Viewed 85

I want to change a @State var variable whenever a row in a list is being selected. Similar to what didSelectRow does in UIKit. That means when tapping on "One" the text on the right-hand side should change from "Nothing selected" to "One".

enter image description here

Here's my current implementation. However, tapping on a row does nothing at all.

struct ContentView: View {
    
    @State var items = [Item(id: 1, text: "One"), Item(id: 2, text: "Two"), Item(id: 3, text: "Three")]
    @State var selectedItem: Item? = nil
    
    var body: some View {
        GeometryReader { geometry in
            HStack(alignment: .center) {
                List(items, selection: $selectedItem) { item in
                    Text(item.text)
                }
                .frame(width: geometry.size.width / 2.5, height: geometry.size.height)
                .listStyle(InsetGroupedListStyle())
                
                Text(selectedItem?.text ?? "Nothing selected")
            }
        }
    }
}

struct Item: Identifiable, Hashable {
    var id: Int
    var text: String
}

How can I change the text when someone taps a row?

2 Answers

Selection in List works only if EditMode is in active state, so you need to handle it manually, something like

var body: some View {
    GeometryReader { geometry in
        HStack(alignment: .center) {
            List(items) { item in
                Text(item.text)
                            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                selectedItem = item
                            }
            }
            .frame(width: geometry.size.width / 2.5, height: geometry.size.height)
            .listStyle(InsetGroupedListStyle())
            
            Text(selectedItem?.text ?? "Nothing selected")
        }
    }
}

and if needed to highlight background than also do it manually.

You can use Button inside your List, and then select the Item in their action like this

List(items, id:\.self, selection: $selectedItem) { item in
    Button(action: {
        self.selectedItem = item
    })
    {
        Text(item.text)
    }
}
Related