Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI + Dynamic action closure for Button

I am exploring SwiftUI and I was able to create a subclass of Button.

The subclass contains image & title properties, which makes it a reusable component.

But I am not able to define dynamic action behavior for Button class.

Please refer code below.

Subclass of Round 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)
        }
    }
}

Example usage:

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)
}

You will see that action block print a message here.

I would like to know how we can pass a function for a button's action event?

like image 509
Kampai Avatar asked Jun 08 '26 07:06

Kampai


1 Answers

Button update ...

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))
            }
    ...

Usage update ...

RoundButton(image: "chat", title: "message") {
    print("Button pressed")
}
like image 176
Asperi Avatar answered Jun 10 '26 07:06

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!