Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - SwiftUI: How to make entire shape recognize gestures when stroked?

I'm creating a custom button in SwiftUI using some shapes.
As a minimal example, I have a filled rectangle, enclosed by a stroked circle (no fill). This is wrapped in a ZStack and a TapGesture is added to that. It works, but my only issue is that the empty space between the square and the circle is not tappable.

How can I make everything inside the circle tappable, without adding a fill to the circle?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to define the hit area, with modifier .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()
      }
    )
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...