SwiftUI按钮在点击而非释放时立即执行动作

4

我想在 SwiftUI Button 被点击/轻敲后立即调用该操作。我该如何实现?

1个回答

8

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接