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