46 - Customize the Appearance of a Button in SwiftUI

It’s important to customize the appearance of a button to make it consistent with the overall design of your app. SwiftUI makes this easy.

Here’s an example:

struct ContentView: View {
  var body: some View {
    Button("Press Me!") {
      // Button action goes here
    }
    .padding()
    .background(.orange)
    .foregroundColor(.white)
    .font(.title2)
    .clipShape(RoundedRectangle(cornerRadius: 10))
  }
}

Your preview should look like this:

Use view modifiers to customize how a button looks in SwiftUI.

This code creates a button in SwiftUI and applies a number of modifiers to change its appearance and functionality.

Here is a breakdown of the code:

One thing to note is that these modifiers are applied in order. So, for example, the padding is applied first, then the background color, and so on. The order of these modifiers can sometimes affect the resulting appearance. In this case, the button will have padding, then the background color will cover the button and its padding, and then the clipping will be applied to the button including its padding.

This would produce a button with white text saying “Press Me!”, an orange background, a bit of padding around the text, and rounded corners.

To summarize, you can customize the appearance of a button in SwiftUI by modifying its background and foreground colors, font styling and corner radius. Use the backgroundforegroundColorfont and clipShape modifiers to achieve this.