当颜色清晰 SwiftUI 时,点击操作不起作用

jsb*_*eJS 11 ios swift swiftui

tapAction是不是当我的识别水龙头foregroundColorIS clear。当我去除颜色时,它工作正常。

那是我的代码:

ZStack {
    RoundedRectangle(cornerRadius: 0)
        .foregroundColor(Color.clear)
        .frame(width: showMenu ? UIScreen.main.bounds.width : 0)
        .tapAction {
            self.showMenu.toggle()
        }
    
    RoundedRectangle(cornerRadius: 5)
        .foregroundColor(Color.green)
        .shadow(radius: 5, y: 2)
        .padding(.trailing, 50)
        .frame(width: showMenu ? UIScreen.main.bounds.width : 0)
}
.edgesIgnoringSafeArea(.top)
Run Code Online (Sandbox Code Playgroud)

51N*_*1N4 17

准确的方法是.contentShape(Rectangle())在视图上使用。本教程中描述:

由 Paul Hudson @twostraws控制的可点击区域

VStack {
    Image("Some Image").resizable().frame(width: 50, height: 50)
    Spacer().frame(height: 50)
    Text("Some Text")
}
.contentShape(Rectangle())
.onTapGesture {
    print("Do Something")
}
Run Code Online (Sandbox Code Playgroud)

如何控制视图的可点击区域使用内容形状stackoverflow

  • 这至少在一种情况下不起作用(即我的情况)。我有一个 SpriteKit 视图,我试图响应点击。这个答案在那种情况下不起作用。 (3认同)
  • 已编辑并附评论 (2认同)

pro*_*ace 12

这是组件

struct InvisibleButton: View {

    let action: (() -> Void)?

    var body: some View {
        Color.clear
        .contentShape(Rectangle())
        .onTapGesture {
            action?()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:将你的视图和InbisibleButton放入ZStack中

ZStack {
     **yourView()**
     InvisibleButton {
        print("Invisible button tapped")
     }
}
Run Code Online (Sandbox Code Playgroud)

您还可以创建一个修饰符来简化使用:

struct InvisibleButtonModifier: ViewModifier {

    let action: (() -> Void)?

    func body(content: Content) -> some View {
        ZStack {
            content
            InvisibleButton(action: action)
        }

    }
}


     **yourView()**
     .modifier(InvisibleButtonModifier {
        print("Invisible button tapped")
      })
Run Code Online (Sandbox Code Playgroud)

但是,如果您的 SwiftUI 视图有一个 UIKit 视图作为子视图,则必须设置 Color.gray.opacity(0.0001) 以便忽略 UIView 的触摸


rob*_*off 10

我还发现填充的形状Color.clear不会生成可点击的区域。

这里有两种解决方法:

  1. 使用Color.black.opacity(0.0001)(即使在每通道 10 位的显示器上)。这会生成一种非常透明的颜色,不会对您的外观产生影响,并会生成一个填充其框架的可点击区域。我不知道 SwiftUI 是否足够智能以跳过渲染颜色,所以我不知道它是否有任何性能影响。

  2. 使用 aGeometryReader获取帧大小,然后使用contentShape生成可点击区域:

    GeometryReader { proxy in
        Color.clear.contentShape(Path(CGRect(origin: .zero, size: proxy.size)))
    }
    
    Run Code Online (Sandbox Code Playgroud)