SwiftUI:如何在抚摸时使整个形状识别手势?
SwiftUI: How to make entire shape recognize gestures when stroked?
我正在使用一些形状在 SwiftUI 中创建自定义按钮。
作为一个最小的例子,我有一个填充的矩形,由一个描边圆(无填充)包围。它被包裹在 ZStack 中,并向其中添加了 TapGesture。它有效,但我唯一的问题是方形和圆形之间的空 space 不可点击。
如何在不向圆圈添加填充的情况下使圆圈内的所有内容都可点击?
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():
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 中创建自定义按钮。
作为一个最小的例子,我有一个填充的矩形,由一个描边圆(无填充)包围。它被包裹在 ZStack 中,并向其中添加了 TapGesture。它有效,但我唯一的问题是方形和圆形之间的空 space 不可点击。
如何在不向圆圈添加填充的情况下使圆圈内的所有内容都可点击?
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():
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()
}
)
}
}