首页 > 解决方案 > 滚动视图下的 SwiftUI 点击

问题描述

绿色的点击手势不起作用。有人对此有解决方案吗?

ZStack {
    Color.green
        .onTapGesture {
            print("green")
        }
    ScrollView {
        VStack {
            Spacer(minLength: 500)
            Color.red
                .onTapGesture {
                    print("red")
                }
                .frame(height: 800)
        }
    }
}

标签: swiftswiftuiscrollviewswiftui-scrollview

解决方案


你想要的东西是不可能的,因为 ScrollView 在绿色视图之上,但是有这样的方法:

    struct ContentView: View {
    
    func greenFunction() { print("green") }
    
    var body: some View {

        ZStack {
            
            Color.green.onTapGesture { greenFunction() }

            ScrollView {

                VStack(spacing: 0) {
                    
                    Color.white.opacity(0.01).frame(height: 500).onTapGesture { greenFunction() }
                    
                    Color.red.frame(height: 800).onTapGesture { print("red") }
                    
                }
            }

        }
        
        
        
    }
}

推荐阅读