Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

Use HStacks or VStacks to group buttons.
Use HStacks or VStacks to group buttons.

This code does the following:

  • VStack arranges its child views in a vertical line. Here, you use it to group the horizontal and vertical button groups.

  • HStack arranges its child views in a horizontal line. In this example, it groups the buttons horizontally.

  • Button("Color", action: {}).foregroundColor(.color) Inside each HStack or VStack, you create a Button view for each color. The Button view takes two arguments: a titleKey and an action. The action is a closure that runs when the button is tapped - here, you’re leaving it empty {}. The titleKey is a shortcut to just add a Text with the input of titleKey that 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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.