SwiftUI + 按钮的动态动作关闭

Kam*_*pai 1 button swift swiftui

我正在探索 SwiftUI,并且能够创建Button.

子类包含image&title属性,这使其成为可重用的组件。

但是我无法为Button类定义动态动作行为。

请参考下面的代码。

圆形按钮的子类:

struct RoundButton: View {
    var image: String
    var title: String
    var body: some View {
        VStack {
            Button(action: {
                print("Button pressed")
            }){
                Image(image)                
                   .renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.template))
            }
            .frame(width: 40, height: 40)
            .background(Color.blue)
            .cornerRadius(20)
            .accentColor(.white)

            Text(title)
                .font(.footnote)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

HStack(alignment: .center) {
    Spacer(minLength: 50)
    RoundButton(image: "chat", title: "message")
    Spacer()
    RoundButton(image: "call", title: "call")
    Spacer()
    RoundButton(image: "video", title: "video")
    Spacer()
    RoundButton(image: "mail", title: "mail")
    Spacer(minLength: 50)
}
Run Code Online (Sandbox Code Playgroud)

您将action在此处看到该块打印一条消息。

我想知道我们如何为按钮的动作事件传递函数?

Asp*_*eri 6

按钮更新...

struct RoundButton: View {
    var image: String
    var title: String
    var action: () -> Void

    var body: some View {
        VStack {
            Button(action: action){
                Image(image)
                   .renderingMode(Image.TemplateRenderingMode?.init(Image.TemplateRenderingMode.template))
            }
    ...
Run Code Online (Sandbox Code Playgroud)

使用更新...

RoundButton(image: "chat", title: "message") {
    print("Button pressed")
}
Run Code Online (Sandbox Code Playgroud)