SwiftUI 按钮无法通过覆盖点击

tHa*_*art 5 button swift swiftui

我有一个带有覆盖层的按钮,但它不可点击。如果我去掉覆盖层,它就变得可点击。我怎样才能让它与覆盖层一起工作?

Button {
                UIImpactFeedbackGenerator(style: .light).impactOccurred()
                UIPasteboard.general.string = viewModel.promoCode?.code ?? ""
            } label: {
                HStack {
                    Text(viewModel.promoCode?.code ?? "")
                        .foregroundColor(Color(UIColor.uStadium.primary))
                        .font(Font(UIFont.uStadium.helvetica(ofSize: 14)))
                        .padding(.leading, 20)
                    Spacer()
                    Image("copyIcon")
                        .foregroundColor(Color(UIColor.uStadium.primary))
                        .padding(.trailing, 20)
                }

            }
            .overlay (
                RoundedRectangle(cornerRadius: 8)
                    .stroke(Color(UIColor.uStadium.primary), style: StrokeStyle(lineWidth: 2, dash: [10]))
                    .frame(height: 42)
                    .background(Color(UIColor.uStadium.primary.withAlphaComponent(0.2)))
            )
            .frame(height: 42)
            .cornerRadius(8)
Run Code Online (Sandbox Code Playgroud)

Seu*_*jun 7

另一个解决方案是.allowsHitTesting(false)overlay.

触摸不起作用的原因是覆盖修改器在当前视图前面分层了一个辅助视图。因此,当用户点击按钮时,他们实际上是在点击重叠视图。

阻止allowsHitTesting(false)视图接收任何类型的点击,并且任何点击都会自动继续通过视图到达其后面的任何内容。

简单的例子:

struct ContentView: View {
    var body: some View {
        Button {
            print("dd")
        } label: {
            Image(systemName: "house").resizable().frame(width: 50, height: 50)
        }
        .overlay (
            RoundedRectangle(cornerRadius: 8).allowsHitTesting(false)
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

和触摸工作!