ZStack中的手势阻止按钮

时间:2019-10-21 20:46:00

标签: swift swiftui gesture

我在ZStack的矩形中添加了一个手势。我有一个VStack,它是按钮的视图或菜单。当我将手势添加到“矩形”时(因为我需要检测菜单按钮后面那个视图上的轻击),因此按钮无法从设备上的用户那里接收交互。我的按钮后面有矩形,它们确实显示在矩形上方。在模拟器上,它工作得很好,但在设备上却不能。任何帮助将不胜感激社区。谢谢!

var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(Color.black.opacity(0.01))
                .gesture(DragGesture(minimumDistance: 0)
                    .onChanged({ (value) in
                    self.store.tapped = true
                }))
            VStack(alignment: .leading, spacing: 0) {
                //menu buttons
                HStack(alignment: .center, spacing: 18.5) {
                    someView()
                        .environmentObject(self.anotherStore)
                        .frame(width: 145, height: 22)
                    self.otherSubviews()
                }
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 37, alignment: .leading)
                .padding(EdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6))
                //menu detail view
                self.detailView()
                }
            .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 12))
        }
    }

我尝试将矩形的.zIndex都更改为-1,对于菜单视图则更改为更高的值。它什么都不会改变

我希望Rectangle可以接收来自用户的交互(抽头),并且VStack按钮也可以接收用户的交互。

1 个答案:

答案 0 :(得分:0)

弄清楚,在背景中有手势的视图需要确保其他视图具有.contentShape(Specify A Shape)

在Apple文档中声明

    /// Returns a new view that defines the content shape for
    /// hit-testing `self` as `shape`.

我在.contentShape(Rectangle())上添加了VStack,它允许点击按钮的菜单视图以及允许点击背景的Rectangle视图。

更新后的代码有答案

var body: some View {
        ZStack {
            Rectangle()
                .foregroundColor(Color.black.opacity(0.01))
                .gesture(DragGesture(minimumDistance: 0)
                    .onChanged({ (value) in
                    self.store.tapped = true
                }))
            VStack(alignment: .leading, spacing: 0) {
                //menu buttons
                HStack(alignment: .center, spacing: 18.5) {
                    someView()
                        .environmentObject(self.anotherStore)
                        .frame(width: 145, height: 22)
                    self.otherSubviews()
                }
                .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 37, alignment: .leading)
                .padding(EdgeInsets(top: 0, leading: 6, bottom: 0, trailing: 6))
                //menu detail view
                self.detailView()
                }.contentShape(Rectangle()) //Define a tappable area
            .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 12))
        }
    }