Ios 列表选择不更改值

Ios 列表选择不更改值,ios,swift,swiftui,Ios,Swift,Swiftui,每当选择列表中的一行时,我想更改@State var变量。与UIKit中的didSelectRow类似。这意味着当点击“一”时,右边的文本应该从“未选择”变为“一” 这是我当前的实现。然而,点击一行并没有任何作用 struct ContentView: View { @State var items = [Item(id: 1, text: "One"), Item(id: 2, text: "Two"), Item(id: 3, te

每当选择列表中的一行时,我想更改
@State var
变量。与UIKit中的
didSelectRow
类似。这意味着当点击“一”时,右边的文本应该从“未选择”变为“一”

这是我当前的实现。然而,点击一行并没有任何作用

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
}

当有人点击一行时,如何更改文本?

只有当
编辑模式处于活动状态时,
列表中的选择才会起作用,因此您需要手动处理它,例如

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

如果需要突出显示背景,也可以手动操作。

您可以在列表中使用
按钮,然后像这样在操作中选择项目

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

就这样!非常感谢你。高亮显示单元格时,是否只需为
contentShape(Rectangle()
)上色?