SwiftUI GroupBox Tutorial
In SwiftUI Group Boxes can be used to combine related views. It has a predefined styling of a background with rounded corners. The content is automatically placed inside a VStack. In this tutorial a Groupbox is displayed with a label field and one with custom styling. This tutorial is built for iOS14 and Xcode 12, which can be download at the Apple developer portal.
Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select App template in the Application section and then click Next.
Enter SwiftUIGroupBoxTutorial as the Product Name, select SwiftUI as Interface, SwiftUI App as Life Cycle and Swift as Language. Deselect the Include Tests checkbos and click Next. Choose a location to save the project on your Mac.
In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.
In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to
struct ContentView: View { @State private var name = "" var body: some View { VStack { // 1. GroupBox(label: Label("Heart rate", systemImage: "heart.fill").font(.largeTitle)) { Text("69 BPM").font(.title) } // 2. GroupBox { Text("Enter your name").font(.title) TextField("name", text: $name) } Spacer() }.padding(.horizontal) } }
The Groupbox has a text label built in, for which the default formatting can be overridden.
The Groupbox can also be used without the prebuilt label to create own custom styling.
Go to the Preview to view the two different GroupBox Views.
The source code of the SwiftUIGroupBoxTutorial can be downloaded at the ioscreator repository on Github.
















