GroupBox View in SwiftUI 3

GroupBox View in SwiftUI 3

A GroupBox View is a simple way for you to create simple stylized views on your interface. You can create a box to house your content and handles stacking automatically.

One of the new types of views introduced on the new version of SwiftUI, at WWDC 2021, was the GroupBox View. As in the documentation, a GroupBox View is a stylized view that gives you an iOS style view in which you can place your content. It works as a pretty container to help you highlight a piece of information in your interface. Also, you can stack them and SwiftUI will handle the colors for you.

Apple Developer Documentation

Documentation Page for GroupBox View

Let's have a look at how this works.

To create a GroupBox is quite simple, just create aGroupBox view and place the content you want to display inside it in its content block. If your device is set for light mode the result shows the content inside a light gray box.

GroupBox {
	Text("**E-mail:** myemail@mail.com")
}

Simple GroupBox view.

If you stack GroupBoxes, SwiftUI will change the colors of each GroupBox view to represent it. It looks much better in dark mode.

GroupBox {
	Text("**E-mail:** myemail@mail.com")

	GroupBox {
		Text("Not available on the weekends")
	}
}

Stacked GroupBox views.

Examples of stacked GroupBoxes on light mode (left) and dark mode (right).

Lastly, you can also initialize a GroupBox with a Label. The Label will be positioned as the title of the GroupBox container.

GroupBox(label: Label("Important", systemImage: "exclamationmark.triangle")) {
	HStack {
		Text("Not available on the weekends.")
			.padding()
		Spacer()
	}
}

Example of a GroupBox view with a Label.

Example of a GroupBox view with a Label on dark mode.

If you want to see an example of how you can use GroupBox on a more complex interface layout, the following snippet uses it to replicate the interface of a Detailed Contact Cards from the CareKit framework:

Using the new view GroupBox from SwiftUI 3 released for iOS 15 on WWDC 2021 to replicate the interface of a Detailed Contact Card View from the CareKit framework. You can see the reference view at: https://developer.apple.com/design/human-interface-guidelines/carekit/overview/views/#contacts
Using the new view GroupBox from SwiftUI 3 released for iOS 15 on WWDC 2021 to replicate the interface of a Detailed Contact Card View from the CareKit framework. You can see the reference view at:...

Code snippet of a SwiftUI Interface example using GroupBox.