How to Use Button in SwiftUI: Simple Guide with Examples
In SwiftUI, you create a
Button by providing a label and an action closure that runs when the button is tapped. Use Button(action: { }) { Text("Label") } to define a button with a text label and a tap action.Syntax
The basic syntax of a Button in SwiftUI includes an action closure and a label view. The action runs when the button is tapped, and the label defines what the button looks like.
action: Code to execute on tap.label: A view that shows the button’s content, often text or an image.
swift
Button(action: {
// Code to run when tapped
}) {
Text("Button Label")
}Output
A tappable button showing the text "Button Label"
Example
This example shows a button that prints a message to the console when tapped. It demonstrates how to create a button with a text label and an action closure.
swift
import SwiftUI struct ContentView: View { var body: some View { Button(action: { print("Button was tapped!") }) { Text("Tap Me") .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) } } }
Output
A blue rounded button labeled "Tap Me" that prints "Button was tapped!" to the console when tapped
Common Pitfalls
Common mistakes when using Button in SwiftUI include:
- Forgetting to provide the
actionclosure, which means the button does nothing. - Using a label that is not a view, like a plain string without wrapping it in
Text. - Not styling the button, which can make it hard to see or tap.
swift
/* Wrong: Missing action closure */ // Button("Tap Me") // This is valid but less flexible /* Right: Provide action and label */ Button(action: { print("Tapped") }) { Text("Tap Me") }
Quick Reference
- Button(action:label:): Creates a button with an action and a label view.
- Label: Can be
Text,Image, or any custom view. - Styling: Use modifiers like
.padding(),.background(), and.cornerRadius()to style buttons. - Accessibility: Use
.accessibilityLabel()to improve screen reader support.
Key Takeaways
Use Button with an action closure and a label view to create tappable buttons in SwiftUI.
Wrap button labels in views like Text or Image for proper display.
Always provide an action closure to define what happens on tap.
Style buttons with modifiers to improve appearance and usability.
Test buttons to ensure they respond correctly and are accessible.