SwiftUI:如何使整个形状在笔触时可以识别手势?

时间:2019-08-13 09:51:58

标签: swift swiftui

我正在使用某些形状在SwiftUI中创建自定义按钮。
作为最小的示例,我有一个填充的矩形,并用描边的圆圈将其包围(不填充)。它包装在ZStack中,并在其中添加了TapGesture。它可以工作,但是我唯一的问题是正方形和圆形之间的空白空间不可轻敲。

如何在不向圆上添加填充的情况下使圆内的所有内容都可轻敲?

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 个答案:

答案 0 :(得分:4)

您需要使用修饰符.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()
      }
    )
  }
}