Create a Group of Buttons in SwiftUI
Written by Team Kodeco
Creating a group of buttons is a common task when designing user interfaces. SwiftUI makes this quite easy with HStack or VStack views.
In the following example, you create two groups of buttons, each representing a different color, and color the button labels to match their respective colors. You’ll then arrange both the horizontal and vertical groups on the same preview screen for comparison:
struct ContentView: View {
var body: some View {
VStack {
// Horizontal group of buttons
HStack {
Button("Red", action: {})
.foregroundColor(.red)
Button("Green", action: {})
.foregroundColor(.green)
Button("Blue", action: {})
.foregroundColor(.blue)
}
Divider()
// Vertical group of buttons
VStack {
Button("Red", action: {})
.foregroundColor(.red)
Button("Green", action: {})
.foregroundColor(.green)
Button("Blue", action: {})
.foregroundColor(.blue)
}
}
}
}
Your preview should look like this:
This code does the following:
-
VStackarranges its child views in a vertical line. Here, you use it to group the horizontal and vertical button groups. -
HStackarranges its child views in a horizontal line. In this example, it groups the buttons horizontally. -
Button("Color", action: {}).foregroundColor(.color)Inside eachHStackorVStack, you create aButtonview for each color. TheButtonview takes two arguments: atitleKeyand an action. Theactionis a closure that runs when the button is tapped - here, you’re leaving it empty{}. ThetitleKeyis a shortcut to just add aTextwith the input oftitleKeythat visually represents the button. You then use the.foregroundColor(.color)modifier to color each label to match its color name. -
Divider()creates a visual separation between the horizontal and vertical button groups.
Creating and organizing groups of buttons in SwiftUI is both straightforward and powerful. It gives you the capability to easily arrange related buttons and create clean and intuitive user interfaces. With additional customization options, such as coloring and grouping views, you can further tailor your interface to suit your needs.