一旦单击按钮,SwiftUI就会执行按钮操作,而不是单击释放

时间:2020-08-08 14:52:49

标签: ios button swiftui

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

1 个答案:

答案 0 :(得分:5)

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