SwiftUI:如何使整个形状在描边时识别手势?

3
我正在使用一些形状在SwiftUI中创建自定义按钮。
作为一个最小的例子,我有一个填充的矩形,被描边圆圈(没有填充)包围。这被包装在一个ZStack中,并添加了TapGesture。它可以工作,但我的唯一问题是正方形和圆之间的空白部分不能被点击。
如何使圆圈内的所有内容可点击,而不添加圆的填充?

最初的回答:
您可以尝试使用overlayModifier(叠加修饰符)来覆盖整个ZStack,然后将tap手势附加到该修饰符。这将使整个按钮区域都变得可点击,而不仅仅是矩形和圆的重叠区域。
这是具体的代码示例:
``` .overlay( Circle() .stroke(lineWidth: 2) ) .contentShape(Circle()) .onTapGesture { // handle tap gesture here } ```
struct ConfirmButton: View {
  var action: () -> Void

  var body: some View {
    ZStack {
      Circle()
        .stroke(Color.purple, lineWidth: 10.0)
        .padding(5)
      Rectangle()
        .fill(Color.red)
        .frame(width: 200, height: 200, alignment: .center)
    }.gesture(
      TapGesture()
        .onEnded {
          print("Hello world")
          self.action()
      }
    )
  }
}

enter image description here

1个回答

9
您需要使用修饰符.contentShape()来定义点击区域:
struct ConfirmButton: View {
  var action: () -> Void

  var body: some View {
    ZStack {
      Circle()
        .stroke(Color.purple, lineWidth: 10.0)
        .padding(5)
      Rectangle()
        .fill(Color.red)
        .frame(width: 200, height: 200, alignment: .center)
    }.contentShape(Circle())
     .gesture(
      TapGesture()
        .onEnded {
          print("Hello world")
          self.action()
      }
    )
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接