SwiftUI:如何在抚摸时使整个形状识别手势? [英] SwiftUI: How to make entire shape recognize gestures when stroked?

查看:27
本文介绍了SwiftUI:如何在抚摸时使整个形状识别手势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些形状在 SwiftUI 中创建自定义按钮.
作为一个最小的例子,我有一个实心矩形,由一个描边圆(无填充)包围.它被封装在一个 ZStack 中,并添加了一个 TapGesture.它有效,但我唯一的问题是正方形和圆形之间的空白区域不可点击.

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()
      }
    )
  }
}

推荐答案

你需要定义命中区域,使用修饰符 .contentShape():

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()
      }
    )
  }
}

这篇关于SwiftUI:如何在抚摸时使整个形状识别手势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆