如何在 SwiftUI 中点击视图下的切换?

问题描述:

一个视图(矩形)下有两个视图(Toggle 和 Button):

There are two views (Toggle and Button) under a view (Rectangle):

struct ContentView: View {
        @State var val = false
        
        var body: some View {
            ZStack {
                VStack {
                    Text("Control penetration")
                        .font(.title)
                    
                    Toggle(isOn: $val){EmptyView()}
                    
                    Button(action: {
                        print("Yes! Clicked!")
                    }){
                        Text("Can you click me???")
                    }
                    
                }
                .padding()
                
                Rectangle()
                    .fill(Color.green.opacity(0.2))
                    .allowsHitTesting(false)
            }
        }
    }

我使用 allowedHitTesting() 让点击穿透到底部.

I use allowsHitTesting() to make the click penetrate to the bottom.

但是只有Button可以响应点击,Toggle不能!

But only the Button can respond to click, the Toggle can not!

这是怎么回事?我怎样才能让 Toggle 也响应点击?非常感谢!

What's wrong with it? How can I make the Toggle respond click too? thanks a lot!

这里有可能的解决方法 - 给它明确的点击手势处理程序.使用 Xcode 12/iOS 14 测试

Here is possible workaround - give it explicit tap gesture handler. Tested with Xcode 12 / iOS 14

Toggle(isOn: $val){EmptyView()}
    .onTapGesture {
        withAnimation { val.toggle() }
    }