将视图(例如 Text())的不透明度设置为 0 或将背景设置为 Color.clear 会导致它不被绘制

Setting a View (Text() for example) opacity to 0 or background to Color.clear causes it to not be drawn

我是十年 iOS 老手,但 Swift/SwiftUI 是个新手,所以请保持温柔。我感到困惑的一件事是,如果不透明度设置为零或 .background(Color.clear) .

我想要完成的是将两个按钮放在 HStack 中作为 ZStack 中的第一个成员(所以最“后退”)以确定用户何时双击屏幕左侧或正确的,但我不想实际显示任何内容,只是检测水龙头。我的 hackish 解决方案是将不透明度设置为 0.001。使用该不透明度设置,什么都不可见,我可以使用 .onTapGesture(count:2) 进行检测,但这肯定不是最佳方式。在 UIKit 领域,我很想自己使用屏幕尺寸来处理点击坐标以确定它落在哪一侧,但我不认为这非常“敏捷”,即使不包装 UIKit 类 也是可能的。努力学习,尽可能做到“纯 SwiftUI”。

public var body: some View {
        ZStack {
            HStack {
                VStack {
                    Text("").frame(maxWidth: .infinity, maxHeight:  .infinity)
                    .background(Color.blue)
                    .opacity(0.0001) //hack workaround, setting opacity to 0.0 and it's like the view isn't even drawn or present (the onTapGesture doesn't get recognized because the VStack has no size when the Text frame is zero and that's the only point! Interestingly setting the background to Color.clear creates the same issue
                }.onTapGesture(count: 2) {
                    print("got a double tap on the LEFT side scroll button")
                }
                
                
                VStack {
                    Text("").frame(maxWidth: .infinity, maxHeight:  .infinity)
                        .background(Color.yellow)
                        .opacity(0.0001)//hack workaround, setting opacity to 0.0 and it's like the view isn't even drawn or present (the onTapGesture doesn't get recognized because the VStack has no size when the Text frame is zero and that's the only point! Interestingly setting the background to Color.clear creates the same issue
                }.onTapGesture(count: 2) {
                    print("got a double tap on the RIGHT side scroll button")
                }
            }
            
            [subsequent members of the ZStack removed as they're not relevant to the question]
    }
}

我想我的问题是:

a) 使用什么是不可见的,但仍然可以检测到 onTapGesture?

b) 如果不透明度为零或背景设置为清除,关于为什么 Text() 和其他视图基本上不存在的一些知识?

谢谢!

a) what to use that's invisible but still layed out to detect onTapGesture?

我们可以使用 .contentShape 修饰符使任何区域,甚至是完全透明的区域都可以点击(又名 hit-testable),例如:

    Color.clear
        .frame(width: 100, height: 100)
        .contentShape(Rectangle())
        .onTapGesture {
            print(">>> Tapped!")
        }

b) some knowledge about why Text() and other views basically don't exist if opacity is zero or background is set to clear?

SwiftUI 将视图渲染到一个上下文中(它与 UIKit 相反,其中每个 UIView 视图都渲染自身),因此当视图完全透明时,没有任何东西可以渲染。