使用UIKit时,我在UIView或UIViewController中进行处理。
func touchesBegan(_ touches:设置, 事件:UIEvent?)
如何使用SwiftUI处理触摸事件?
答案 0 :(得分:2)
最简单的方法是添加一个DragGesture。 Check out DragGesture.Value
来了解您所拥有的信息。
Circle()
.gesture(
DragGesture(minimumDistance: 5, coordinateSpace: .global)
.onChanged { value in
self.dragLocation = value.location
}
.onEnded { _ in
self.dragLocation = .zero
}
)
您可以使用minimumDistance: 0
来使手势立即开始更新,类似于UIKit中的touchesBegan(...)
。
答案 1 :(得分:0)
作为另一种方式,我们可以创建自定义按钮。 SwiftUI提供ButtonStyle,PrimitiveButtonStyle等。
https://developer.apple.com/documentation/swiftui/buttonstyle
实际上,Button不会自己创建标签,Button拥有样式,并委托将标签创建为样式。
因此,Style具有makeBody
方法,我们可以获得一个配置对象。
该对象具有从外部传递的标签和isPressed
标志。
isPressed
将更改为touchDown和touchUpInside事件。
我已经创建了自定义按钮样式。在组件触摸时会添加一个覆盖。
示例代码
struct OverlayButton<Content: View>: View {
private let content: Content
init(
@ViewBuilder _ content: () -> Content
) {
self.content = content()
}
var body: some View {
Button(action: {}) { content }
.buttonStyle(_ButtonStyle())
}
private struct _ButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> AnyView {
if configuration.isPressed {
return AnyView(
configuration.label
.background(Color(white: 0.96))
)
} else {
return AnyView(
configuration.label
.background(Color(white: 1, opacity: 0.0001))
)
}
}
}
}
我希望这是你的主意。