How can I tap the Toggle under a View in SwiftUI?

岁酱吖の 提交于 2021-01-28 12:46:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!