HStack:onTapGesture 仅适用于元素

Lup*_*rus 3 swiftui

我有这个例子:

struct ContentView: View {
    
    var body: some View {
        HStack {

            Text("part1")

            Spacer()

            Text("part2")

            Spacer()

            Text("part3")

        }
        .onTapGesture {
            print("tapped")
        }
    }
    
}
Run Code Online (Sandbox Code Playgroud)

问题是,.onTapGesture只有在我点击 a 时才会被调用Text,但如果我点击元素之间的空间则不会。

我试图将 aRectangle().fill(Color.clear)作为 的背景HStack,但它也不起作用(它只是有效,如果我放了 ie Color.blue)。

Asp*_*eri 10

它需要指定内容形状来覆盖所有区域,因为默认情况下只有不透明的东西处理手势

}
.contentShape(Rectangle())      // << here !!
.onTapGesture {
    print("tapped")
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!刚刚发现 `.background(Rectangle().fill(Color(UIColor.systemBackground)))` 也可以工作;) (2认同)