Group
in SwiftUI is a type that collects multiple instances of a content type — like views, scenes, or commands — into a single unit. Group
doesn’t have any visual representation, its just a container much like VStack
and HStack
.
We use a group to collect multiple views into a single instance, without affecting the layout of those views, just like an HStack
, VStack
, or Section
. After creating a group, any modifier applied to the group affects all of that group’s members.
Let’s start with example.
struct DevTechieGroupExample: View {
var body: some View {
VStack {
Text("DevTechie Courses")
.font(.largeTitle)
Group {
Text("SwiftUI")
Text("Combine")
Text("iOS Development")
}.font(.body)
}
}
}
Because we create a group of views with a ViewBuilder
, we can use the group’s initializer to produce different kinds of views from a conditional, and then optionally apply modifiers to them.
The following example uses a Group
to add a navigation bar title, regardless of the type of view the conditional produces.
struct DevTechieGroupExample: View {
@State private var loggedIn = true
var body: some View {
NavigationView {
Group {
if…