How to create a reusable button component in SwiftUI?

I am wondering about best practices when creating a reusable button component in SwiftUI. i.e., a button that I can reuse many places in my project and takes in various parameters and callback functions to perform actions.

I have tried searching online and on forums but I have not found any best practices.

>Solution :

There isn’t a best practice in-terms of an industry standard for buttons, but creating a re-usuable component will go a long way in keeping all UI consistent in the app.

struct CustomButton: View {
  var text: String                     // text to render inside the button
  var submissionHandler: () -> Void   // function that gets called on submission

  var body: some View {
    Button(action: {
      handler()
    }, label: {
      Text(text)
    })
      .accessibility(value: Text("\(text) Button")).   // make sure to include accessibility labels
  }
}

Usage:

var body: some View {
  Text("Rendering Button")
  CustomButton(text: "hello", submissionHandler: {
    print("Handling button submission")
  }

}

You can go a step further and add styling options to this button component that gets conditionally selected based on parameters passed.

Hope this helps!

Leave a Reply