如何在 SwiftUI 中点击视图下的切换? [英] How can I tap the Toggle under a View in SwiftUI?

查看:35
本文介绍了如何在 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() }
    }

这篇关于如何在 SwiftUI 中点击视图下的切换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆