50 - Create a Group of Buttons in SwiftUI

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:

Use HStacks or VStacks to group buttons.

This code does the following:

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.