简体   繁体   中英

List selection not changing value

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" .

在此处输入图像描述

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM