Add a Button in SwiftUI
Written by Team Kodeco
Buttons are essential for creating interactive elements in your user interface. In SwiftUI, you create buttons by using the Button
view.
Here’s an example:
struct ContentView: View {
var body: some View {
Button(action: {
print("Button Pressed")
}, label: {
Text("Press Me!")
})
}
}
In the above example, when the button is pressed, the action closure will be executed, which simply prints a message to the console. The label of the button is set to “Press Me!” using a Text
view. You can customize the appearance of the button by modifying the Text
view.
You can customize the look of a button using view modifiers. Try the following:
struct ContentView: View {
var body: some View {
Button(action: {
print("Button Pressed")
}, label: {
Text("Press Me!")
.font(.largeTitle)
.foregroundColor(.white)
})
.padding()
.background(
LinearGradient(gradient: Gradient(colors: [.purple, .pink]), startPoint: .topLeading, endPoint: .bottomTrailing)
)
.cornerRadius(10)
}
}
The above code adds padding, a gradient background and a corner radius to the button. We also increased the font size of the label and changed its color to white. It should look like the following:
For more details, see the “Buttons in SwiftUI” section in this cookbook.