ios - 单击按钮后立即执行 SwiftUI 按钮操作,而不是单击释放

标签 ios button swiftui

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

最佳答案

这是一种可能的方法 - 使用自定义 ButtonStyle 来注入(inject)自定义触地 Action

使用 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")
        })
    }
}

关于ios - 单击按钮后立即执行 SwiftUI 按钮操作,而不是单击释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63316752/

相关文章:

java - 按下按钮并转到上一个布局

ios - 以编程方式推送、继续、召唤、导航至 View SwiftUI

SwiftUI:如何删除 VStack 中 View 之间的边距?

ios - iOS 中 PkgInfo 的用途是什么

ios - 从 touchesEnded 获取图像名称

android - 如何在一行中对齐 3 个按钮,android?

ios - Swift - 从 View 扩展以编程方式更新 Binding<String> 存储值

iphone - 什么样的下载代码违反了 App Store Review Guideline?

ios - 这是强还是弱?

javascript - 如何创建流畅的动画流动按钮?