[英]SwiftUI handling button/view with onTapGesture and onLongPressGesture with a release action
[英]SwiftUI button action as soon as button is clicked not on click release
我想在 SwiftUI 按钮中单击/点击按钮后立即调用该操作。 我该如何实施?
这是一种可能的方法 - 使用自定义ButtonStyle
来注入自定义触地动作
用 Xcode 12 / iOS 14 测试
struct PressedButtonStyle: ButtonStyle {
let touchDown: () -> ()
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(configuration.isPressed ? Color.gray : Color.blue)
.background(configuration.isPressed ? self.handlePressed() : Color.clear)
}
private func handlePressed() -> Color {
touchDown() // << here !!
return Color.clear
}
}
struct DemoPressedButton: View {
var body: some View {
Button("Demo") {
print(">> tap up") // << can be empty if nothing needed
}
.buttonStyle(PressedButtonStyle {
print(">> tap down")
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.