【问题标题】:SwiftUI: How to make entire shape recognize gestures when stroked?SwiftUI:如何让整个形状在抚摸时识别手势?
【发布时间】:2019-08-13 09:51:58
【问题描述】:

我正在使用一些形状在 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()
      }
    )
  }
}

【问题讨论】:

    标签: swift swiftui


    【解决方案1】:

    你需要定义命中区域,使用修饰符 .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()
          }
        )
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多