如何使用 SwiftUI 处理屏幕触摸事件?
How to Handle screen touch events with SwiftUI?
在使用 UIKit 时,我在 UIView 或 UIViewController 中处理。
func touchesBegan(_ touches: Set,
with event: UIEvent?)
如何使用 SwiftUI 处理触摸事件?
最简单的事情是添加拖动手势。 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(...)
。
作为另一种方式,我们有创建自定义按钮的方法。
SwiftUI 提供了 ButtonStyle、PrimitiveButtonStyle 等。
https://developer.apple.com/documentation/swiftui/buttonstyle
其实Button并没有自己创建标签,Button有Style,委托Style创建标签。
所以,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))
)
}
}
}
}
希望这是你的想法。
在使用 UIKit 时,我在 UIView 或 UIViewController 中处理。
func touchesBegan(_ touches: Set, with event: UIEvent?)
如何使用 SwiftUI 处理触摸事件?
最简单的事情是添加拖动手势。 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(...)
。
作为另一种方式,我们有创建自定义按钮的方法。 SwiftUI 提供了 ButtonStyle、PrimitiveButtonStyle 等。
https://developer.apple.com/documentation/swiftui/buttonstyle
其实Button并没有自己创建标签,Button有Style,委托Style创建标签。
所以,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))
)
}
}
}
}
希望这是你的想法。