Skip to main content

Working with buttons

To begin, what is a button in SwiftUI?

struct MainView: View {
    var body: some View {
        Button(action: {}) {
            Text("My button in SwiftUI")
        }
    }
}

This code snippet will create a view that contains a button. That button will display some text My button in SwiftUI that when tapped fires off a blank action.  However, if you are like me, I don't have a need for the default type of functionality.  The SwiftUI button needs to do more!.  Such as managing the colour (foreground and background) and what happens when the button is tapped. There are a several ways to do this of which I address two of them here:

  • .foregroundColor() and .background(); or
  • Using a ButtonStyle

To add foreground, background colours and corner radius, this is a quick add on through adding:

struct MainView: View {
    var body: some View {
        Button(action: {}) {
            Text("My button in SwiftUI")
        }
        .background(Color.black)
        .foregroundColor(Color.white)
        .cornerRadius(10.0)
    }
}

Of course if you want to increase the transparency of the background add on opacity

.background(Color.black.opacity(0.8))

This is pretty simple stuff to make your button meet your requirements.

 

Button Style

​​​​​​​What about if you want to use the button theming over and over again or manage the state of it.  Well that is where ButtonStyle kicks into play.  You can set up a struct for the button 

struct NextButton: ButtonStyle {
  
  func makeBody(configuration: Self.Configuration) -> some View {
    configuration
    .label
    .foregroundColor(Color.white)
    .padding(5)
    .background(Color.black.opacity(0.8))
    .cornerRadius(10.0)
  }
  
}

With the NextButton style create it is applied to the button:

    Button(action: {}) {
         Text("This is a Button in SwiftUI")
      }
      .buttonStyle(NextButton())

In the sample code above, you can see that added is the foreground and background colours, padding and a corner radius.

 

 

Related articles

Andrew Fletcher12 Aug 2022
Using SwiftUI URLComponent to change a URL's scheme
The challenge I was facing, I had written a script to scan barcodes and use Google book API to view the contents.  However, a snippet of the JSON response { "contentVersion": "0.2.0.0.preview.0", "panelizationSummary": { "containsEpubBubbles": false, ...