Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Customize the Appearance of a Button in SwiftUI
Written by Team Kodeco

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.
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:

  • Button("Press Me!") { } creates a new Button with the title Press Me!. The text within the {} is the action that will be executed when the button is pressed. In this case, there is no action defined yet.

  • .padding() adds padding around the button. Padding is space around the content of a view, which is the button in this case. Without any arguments, it adds a system default amount of space on all sides of the button.

  • .background(.orange) sets the background color of the button to orange.

  • .foregroundColor(.white) sets the color of the text of the button to white.

  • .font(.title2) sets the font of the button’s title to title2, which is a predefined font style that is smaller than title but larger than headline.

  • .clipShape(RoundedRectangle(cornerRadius: 10)) clips the button into the shape of a rectangle with rounded corners. The cornerRadius: 10 means the corners of the rectangle will be rounded with a radius of 10.

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 background, foregroundColor, font and clipShape modifiers to achieve this.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.