如何检测 SwiftUI 中列表单元格行上的点击?

bog*_*gen 14 swiftui

给定一个基本的Listwith Text,我怎样才能使从屏幕左侧到右侧的整个“单元格”在 a 中可点击List,而不仅仅是“Hello world”文本?

    List {
         VStack {
             Text("Hello world")
         }    
         .contentShape(Rectangle())
         .onTapGesture {
            print("Tapped cell")  // This only triggers when you directly tap the Text
         }
     }
Run Code Online (Sandbox Code Playgroud)

RTX*_*mer 24

添加一个按钮,现在整个单元格都可以点击:

VStack {
    Button(action: {
        print("Tapped")
    }) {
        Text("Hello world")
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 提示:您可以使用 `.buttonStyle(.plain)` 禁用蓝色色调 (3认同)

Chu*_*k H 16

实际上,您真正需要做的就是确保整个单元格都充满内容。将 更改VStack为 anHStack并添加 aSpacer()会给你你想要的。

    List {
         HStack {
             Text("Hello world")
             Spacer()
         }
         .contentShape(Rectangle())
         .onTapGesture {
            print("Tapped cell")  // This triggers when you tap anywhere in the cell
         }
     }
Run Code Online (Sandbox Code Playgroud)

  • 使用 `.onTapGesture` 会降低可访问性,因为该行不会在 VoiceOver 中注册为按钮 (4认同)