Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading