对于SwiftUI,默认按钮行为等同于UIKit的“在内部向上触摸”,当您的手指触摸按钮然后在按钮范围内抬起时,该行为会激活。
是否可以将其更改为“触地”,以便在您的手指触摸按钮时立即执行动作关闭?
答案 0 :(得分:3)
您可以使用最小距离为零的DragGesture,并为DOWN(onChanged())或UP(onEnded())定义闭包:
struct ContentView: View {
@State private var idx = 0
var body: some View {
let g = DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({
print("DOWN: \($0)")
}).onEnded({
print("UP: \($0)")
})
return Rectangle().frame(width: 100, height: 50).gesture(g)
}
}
答案 1 :(得分:2)
您可以创建自定义视图修饰符:
extension View {
func onTouchDownGesture(callback: @escaping () -> Void) -> some View {
modifier(OnTouchDownGestureModifier(callback: callback))
}
}
private struct OnTouchDownGestureModifier: ViewModifier {
@State private var tapped = false
let callback: () -> Void
func body(content: Content) -> some View {
content
.simultaneousGesture(DragGesture(minimumDistance: 0)
.onChanged { _ in
if !self.tapped {
self.tapped = true
self.callback()
}
}
.onEnded { _ in
self.tapped = false
})
}
}
struct MyView: View {
var body: some View {
Text("Hello World")
.onTouchDownGesture {
print("View did tap!")
}
}
}
答案 2 :(得分:0)
我设法通过一个简单的按钮修饰符实现了这一点:
struct TouchedButtonStyle: PrimitiveButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration
.label
.onTapGesture(perform: configuration.trigger)
}
}
现在您只需将修饰符分配给您的按钮:
YourButton()
.buttonStyle(TouchedButtonStyle())