问题
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)
}
}
}
I use allowsHitTesting() to make the click penetrate to the bottom.
But only the Button can respond to click, the Toggle can not!
What's wrong with it? How can I make the Toggle respond click too? thanks a lot!
回答1:
Here is possible workaround - give it explicit tap gesture handler. Tested with Xcode 12 / iOS 14
Toggle(isOn: $val){EmptyView()}
.onTapGesture {
withAnimation { val.toggle() }
}
来源:https://stackoverflow.com/questions/63749022/how-can-i-tap-the-toggle-under-a-view-in-swiftui