ios - 单击按钮后立即执行 SwiftUI 按钮操作,而不是单击释放
问题描述
我想在 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")
})
}
}
推荐阅读
- php - 如何在 FancyBox 上使所有图像的纵横比为 1:1?
- angular - 勾选复选框时如何同时执行多个功能
- java - 为什么 Springboot 中的 2 个 Kafka 消费者指的是同一个 Kafka Broker?
- function - 新项目弄乱了我的变量 PowerShell
- javascript - 如何以角度测试组件@Input?
- c - 需要帮助理解来自 ghidra 的反编译代码行
- real-time - 无需服务器的实时文档协作
- svg - 使 SVG 图像的元素在 devtools 中不可扫描
- python - 读取当前麦克风状态
- apache-spark-sql - 将表数据作为二进制文件推送到 UDF