一旦单击按钮,就立即执行SwiftUI按钮操作,而不是单击释放 [英] SwiftUI button action as soon as button is clicked not on click release

查看:52
本文介绍了一旦单击按钮,就立即执行SwiftUI按钮操作,而不是单击释放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在SwiftUI Button中单击/点击按钮后立即调用该动作.我该如何实施?

I want to call the action as soon as the button is clicked/tapped in SwiftUI Button. How can I implement this?

推荐答案

这里是一种可能的方法-使用自定义 ButtonStyle 注入自定义触地动作

Here is a possible approach - to use custom ButtonStyle to inject custom touch down action

通过Xcode 12/iOS 14测试

Tested with 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")
        })
    }
}

这篇关于一旦单击按钮,就立即执行SwiftUI按钮操作,而不是单击释放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆