Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Create a Button in SwiftUI
Written by Team Kodeco

Buttons are essential components of any user interface, allowing users to interact with and initiate actions in your app. In SwiftUI, creating a button is straightforward and customizable.

To create a button, simply use the Button view and pass in your desired label as a parameter. Here’s an example:

struct ContentView: View {
  var body: some View {
    Button("Click me!") {
      // Action to perform when button is tapped
    }
  }
}

Your preview should look like this:

Use the Button view to create a button in SwiftUI.
Use the Button view to create a button in SwiftUI.

In this example, we’ve created a button with the label Click me! and assigned an action to be performed when the button is tapped. The action is defined using a closure, which is wrapped in curly braces {}.

You can customize the appearance of your button by using modifiers such as font, padding and foregroundColor. Here’s an example:

struct ContentView: View {
  var body: some View {
    Button("Submit") {
      // Action to perform when button is tapped
    }
    .font(.headline)
    .padding()
    .foregroundColor(.white)
    .background(.blue)
    .cornerRadius(5)
  }
}

Your preview should look like this:

You can style buttons in SwiftUI with view modifiers.
You can style buttons in SwiftUI with view modifiers.

In this example, you customize the button by setting the font to .headline, adding padding, setting the foreground color to white, setting the background color to blue and rounding the corners using a cornerRadius modifier.

Overall, creating buttons in SwiftUI is quick and easy, and the ability to customize the appearance of your buttons allows you to create a unique and consistent user interface in your app.

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.