【问题标题】:SwiftUI button action as soon as button is clicked not on click release单击按钮后立即执行 SwiftUI 按钮操作,而不是单击释放
【发布时间】:2020-08-08 14:52:49
【问题描述】:

我想在 SwiftUI 按钮中单击/点击按钮后立即调用该操作。我该如何实现?

【问题讨论】:

    标签: ios button swiftui


    【解决方案1】:

    这是一种可能的方法 - 使用自定义 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")
            })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-12
      • 2022-12-02
      • 2014-09-10
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多