SwiftUI - Containers



Containers are the views that carry or display other views in it. Or we can say that containers are used to display other views in a structured layout. They allow us to display or manage child views either in a simple sequence or in a complex hierarchy. They are responsible for how the view will display and behave in the app's interface. It is the most powerful and uses the full feature of SwiftUI.

Containers provide us with the flexibility to arrange the child views in whatever layout we want and can apply changes to individual or whole child views in one go. SwiftUI supports various types of containers, and they are as follows −

  • Stacks

  • List

  • Form

  • ScrollView

  • Group

  • GeometryReader

Stacks

Stacks are used to arrange views in a specified order. SwiftUI supports three types of stack: VStack, HStack and ZStack. VStack is used to arrange views vertically, HStack is used to arrange views horizontally, and ZStack is used to arrange a view above another view or in layers.

You can use them according to the layout of the app. We can also be allowed to nest one view inside another view.

Example

The following SwiftUI program uses stacks.

import SwiftUI
struct ContentView: View {
   var body: some View {
      VStack{
         Text("Tutorials Point")
            .font(.largeTitle)
            .bold()
            .foregroundStyle(.green)
         ZStack{
            Rectangle()
               .frame(width: 200, height: 100)
               .background(.gray)
            Text("Visit")
               .font(.title)
               .bold()
               .foregroundStyle(.white)
         }
      }
   }
}
#Preview {
   ContentView()
}

Output

Containers

List

Lists are the most commonly used container to display data in the single-column format. It displays data in a scrollable container. It displays a collection of data and supports dynamic element generation, selection, modification, etc.

It can also add UI elements such as TextFields, Buttons, Toggle, Sliders, etc. We can create a list with the help of an in-built List View.

Example

The following SwiftUI program creates a list.

import SwiftUI
struct ContentView: View {
   var body: some View {
      Text("Setting").font(.largeTitle)
      List {
         Text("Bluetooth")
         Text("Hotspot")
         Text("Wifi")
      }
   }
}
#Preview {
   ContentView()
}

Output

Containers

Form

Form is used to arrange multiple views into related groups with the scrollable interface. Or we can say that it is a container which contains multiple views that take input from the user. It is commonly used to provide an interface with an interface where users can enter data in different fields.

The key features of the Form view are automatic layout, grouping with sections, and dynamic appearance. We can customize and style the form according to our needs and can use various UI components in it such as TextField, Slider, toggle, etc.

Example

The following SwiftUI program creates a form.

import SwiftUI
struct ContentView: View {
   @State private var name = ""
   @State private var mClass = ""
   @State private var rollNo = 3
   @State private var receiveNewsletter = false
   var body: some View {
      NavigationView {
         Form {
            Section(header: Text("Personal Information")) {
               TextField("Name", text: $name)
               TextField("Class", text: $mClass)
               Stepper("Roll Number: \(rollNo)", value: $rollNo, in: 1...100)
            }            
            Section {
               Button("Submit") {
                  
                  // Action on submit
                  print("Form Submitted")
               }
            }
         }.navigationTitle("User Form")
      }
   }
}
#Preview {
   ContentView()
}

Output

Containers

ScrollView

ScrollView is a special type of container which allows users to display scrollable content. It can scroll either vertically or horizontally, or in both directions.

It is generally used when we want to display a large amount of data that does not fit inside the given screen, such as text, images, etc. By default, it creates a vertical scroll, but we can change it using horizontal and vertical values.

Example

The following SwiftUI program creates a ScrollView.

import SwiftUI
struct ContentView: View {
   var body: some View {
      ScrollView {
         VStack(spacing: 20) {
            ForEach(1...20, id: \.self) { i in
               Text("Branch \(i)")
                  .font(.title)
                  .padding()
                  .frame(maxWidth: .infinity)
                  .background(.mint.opacity(0.2))
                  .cornerRadius(8)
            }
         }.padding()
      }
   }
}
#Preview {
   ContentView()
}

Output

Containers

Group

Group is a container which is used to store multiple views together without affecting the layout of its child view. It does not apply any layout to its data. Instead, it provides a way to organize views. It is a great tool to keep the view hierarchies clean and managable because it divides the view hierarchy in groups.

Example

The following SwiftUI program creates a group of text.

import SwiftUI
struct ContentView: View {
   var body: some View {
      VStack {
         Text("SwiftUI").font(.largeTitle)
         
         Group {
            Text("SwiftUI support declarative programming approach")
            Text("It also provide various modifiers.")
            Text("It is easy to use")
         }.font(.headline).foregroundStyle(.red.opacity(5.2))
      }.padding()
   }
}

#Preview {
   ContentView()
}

Output

Containers

GeometryReader

GeometryReader is a flexible container which allows us to create a view according to the dynamic sizes(that is, dynamic height and width) of the screen or the parent view. Or we can say that it manipulates the size and position of the parent view.

It is useful when we want to create a layout in the specified space. It takes up all the free space of its parent view, so whenever it works with Stack or any other container, it will stretch itself to occupy the specified space.

Example

The following SwiftUI program creates a view using GeometryReader..

import SwiftUI

struct ContentView: View {
   var body: some View {
      GeometryReader { x in
         VStack {
            Text("Width: \(x.size.width)")
            Text("Height: \(x.size.height)")
         }.frame(width: x.size.width, height: x.size.height)
         .background(.pink.opacity(0.2))
      }.frame(height: 200)
   }
}

#Preview {
   ContentView()
}

Output

Containers
Advertisements