Pre Requisites

Download Xcode 12.3 [Latest Version] From Mac App Store

Download »

Youtube Channel

Check Out Our Kavsoft Youtube Channel For More Advanced Tutorials

Visit »


Views And Layout


VStack

A view that arranges its child views in a vertical line.
Syntax

init(alignment: HorizontalAlignment, spacing: CGFloat?, 
content: () -> Content)

In this example we have created a Vstack where all items of the stack are aligned horizontally to the left with a space of 10px between each items of the stack.

Usage

          
  VStack(alignment: .leading, spacing: 10) {
    Text("Placeholder 1")
    Text("Placeholder 2")
    Text("Placeholder 3")
  }
          
        

HStack

A view that arranges its children in a horizontal line.
Syntax

init(alignment: VerticalAlignment, spacing: CGFloat?, 
content: () -> Content)

In this example we have created a Hstack where all the items of the stack aligned vertically on the top with a space of 10px between each items of the stack.

Usage

          
 HStack(alignment: .top, spacing: 15) {     
    Text("Placeholder 1")
    Text("Placeholder 2")
    Text("Placeholder 3")
 }
          
        

ZStack

A view that overlays its children and aligning them in both axes.
Syntax

init(alignment: Alignment = .center,
content: () -> Content)

In this example we have created a ZStack in which each element will overlay on another. Since the alignment is a leading Center, each item will overlay on the left center side.

Usage

          
 ZStack(alignment: Alignment(horizontal: .leading, vertical: .center)) {
   // View 1
   // View 2
   // View 3
 }
          
        

List

A container that presents rows of data arranged in a single column.
Syntax

init(Data, id: KeyPath, selection: Binding>?, 
rowContent: (Data.Element) -> RowContent)

In this example we have created a list with 10 items And the selected row will be captured on the binded $SelectedValue parameter.

Usage

          
 @State var selectedValue : Int? = 0

 List(1...10, id: \.self, selection: $selectedValue) { index in    

  // View.....

 }
          
        

ScrollView

The scroll view displays a scrollable area with all the content in it.
Syntax

init(Axis.Set, showsIndicators: Bool, content: () -> Content)

In this example we have created a ScrollView with the direction of the given axis and shows indicators while scrolling.

Usage

          
  ScrollView(.vertical, showsIndicators: true, content: {
     // Your Scrollable Content....
  })
          
        

GeometryReader

It is a container view that defines the content in it. It can use properties that positions the views within it.
Syntax

init(content: (GeometryProxy) -> Content)

In this example we have created a geometry reader closure with reader property, from which we can get coordinate space data.

Usage

          
 GeometryReader{reader in
                
   // Your View...
   // From reader Property You Can Able To Read Coordinate Space Value...
 }

          
        

TabView

This view uses interactive user interface and switches between multiple child views.
Syntax

init(selection: Binding?, content: () -> Content)

In this example we have created a tab view with two tab items and the selected tab value will be captured in binded $SelectedValue parameter.

Usage

          
  TabView(selection: $selectedValue,content:  {

     // View 1
     Text("View 1").tag(0).tabItem {
       // Tab Button View For View 1...
     }
     // View 2
     Text("View 2").tag(1).tabItem {
       // Tab Button View For View 2...
    }
  })
 
          
        

NavigationView

A view containing a stack of views that allows master view to navigate to detail view.
Syntax

init(content: () -> Content)

In this example we have created a navigation view and decalred a few navigation Bar Properties like title, display mode And navigation bar actions.

Usage

          
  NavigationView{
   // Your View That Needs Navigation To Other Pages...
  }
   // Some Properties...
   .navigationTitle("YOUR TITLE")
   .navigationBarTitleDisplayMode(.inline)
   .toolbar(content: {
     // Navigation Bar Items..
    ToolbarItem(placement: .navigationBarTrailing) {
       // Your Navigation Bar Trailing View....
    }
  })
          
        

LazyVStack

A view that arranges the child views vertically in a line and creates items when required or visible at the screen.
Syntax

init(alignment: HorizontalAlignment, spacing: CGFloat?, 
pinnedViews: PinnedScrollableViews, content: () -> Content)

In this exmaple we have created a LazyVStack where all the items of the stack aligned horizontally at the left with spacing of 10px. Also, it will the pin the section headers at the top of the view when the content scrolls up/down.

Usage

          
  LazyVStack(alignment: .leading, spacing: 10, pinnedViews: [.sectionHeaders], content: {

   // Your Lazy Loading Views....
  })
          
        

LazyHStack

A view that arranges the child views horizontally in a line and creates items when required or visible at the screen.
Syntax

init(alignment: VerticalAlignment, spacing: CGFloat?, 
pinnedViews: PinnedScrollableViews, content: () -> Content)

In this exmaple we have created a LazyHStack where all the items of the stack aligned vertically at the top with the spacing of10px. Also, it will the pin she section footer at The bottom of the view when the content scrolls left/right.

Usage

          
  LazyHStack(alignment: .top, spacing: 10, pinnedViews: [.sectionFooters], content: {

     // Your Lazy Loading Views....
  })
          
        

LazyVGrid

It's a Lazy View that arranges the child views vertically in a grid and load grid items when required or visible at the screen.
Syntax

init(columns: [GridItem], alignment: HorizontalAlignment, 
spacing: CGFloat?, pinnedViews: PinnedScrollableViews,
content: () -> Content)

In this example we have created a grid view with 'n' number of rows, each row having 3 column with the spacing of 10px and each column with spacing of 15px. Each row is aligned horizontally center.

Usage

          
  let columns = Array(repeating: GridItem(.flexible(), spacing: 10), count: 3)
            
  LazyVGrid(columns: columns, alignment: .center, spacing: 15, pinnedViews: [.sectionHeaders], content: {

   // Your Vertical Grid Views...
  })
          
        

LazyHGrid

It's a Lazy View that arranges the child views horizontally in a grid and load grid items when it is required (or) when it is visible at the screen.
Syntax

init(rows: [GridItem], alignment: VerticalAlignment, 
spacing: CGFloat?, pinnedViews: PinnedScrollableViews,
content: () -> Content)

In this example we have created a grid view with 'n' number of columns, each column having 3 row with the spacing of 10px and each row with spacing of 15px. Each column is aligned vertically top.

Usage

          
  let rows = Array(repeating: GridItem(.flexible(), spacing: 10), count: 3)
            
  LazyHGrid(rows: rows, alignment: .top, spacing: 15, pinnedViews: [.sectionHeaders], content: {

     // Your Horizontal Grid Views...
  })
          
        

ScrollViewReader

This is a view that defines its child as a function of a ScrollViewProxy, ScrollViewProxy provides us scrollTo function. Thus with the help of this function we can scroll to anyview that defines it's ID in ScrollView.
Syntax

init(content: (ScrollViewProxy) -> Content)

Usage

          
  ScrollViewReader{reader in
  
   // You Can Use reader Property to Scroll To Those Views...
   // Properties
   // reader.scrollTo("VIEW ID",anchor: .bottom)
  }
          
        

Form

This is a container that groups which allows you to group data entry controls such as text fields,toggles..,etc.
Syntax

init(content: () -> Content)

In this example we created a simple form with its contents.

Usage

          
  Form {
     // Form Content...
     Text("Content 1")
     Text("Content 2")
     Text("Content 3")
  }
          
        

Group

This is to group the views and its content.
Syntax

init(content: () -> Content)

Usage

          
  Group{
     // We Can Group Multiple Views Together....
     Text("View 1")
     Text("View 2")
  }
          
        

GroupBox

This is same as group but it is assigned with a label for that group.
Syntax

init(label: Label, content: () -> Content)

Usage

          
  GroupBox(label: Text("GROUP LABEL")) {
     // Group Content...
     Text("Content 1")
  }
          
        

Section

Section is a view that allows us to specify header (or) footer for that view.
Syntax

init(header: Parent, footer: Footer, content: () -> Content)

Usage

          
  Section(header: Text("HEADER OR FOTTER")) {
     // Section Content....
  }
          
        

OutlineGroup

Outline Group represent a hierarchy of data by using disclosure views. This allows the user to navigate the tree structure by using the disclosure views to expand and collapse branches.
Syntax

init(Data, id: KeyPath, children: KeyPath, content: (DataElement) -> Leaf)

Usage

          
  struct GroupContent: Identifiable {
     var id = UUID().uuidString
     var subContent: [GroupContent]?
     // Other Properties.....
  }
          
  let groupData = [
        
    GroupContent(),
    GroupContent(subContent: [
      GroupContent(),
      GroupContent(),
      GroupContent()
    ]),
    GroupContent(subContent: [
      GroupContent(),
      GroupContent(),
    ])
  ]
       
   // Each Group Has a Sub Group Of the Same Data....
   // So It Will be Expanded....
   OutlineGroup(groupData, children: \.subContent) { content in
          
    Text("\(content.id)")
  }
  .padding()
          
        

DisclosureGroup

This is a view that hides or expands the content inside a view as per the user control.
Syntax

init(LocalizedStringKey, content: () -> Content)

Usage

          
  DisclosureGroup(
     content: {
     // Expanded Content.....
  },
  label: {
     Text("LABEL OR TITLE")
  })
          
        

Spacer

This will automatically fill up all available space on their axis of expansion.
Syntax

init(minLength: CGFloat?)

Divider

It is a view that separates one content from another.
Syntax

init()

Usage

          
  VStack{
                
     //.....SOME VIEWS.....
              
     // minLength is the Minimum Length Between Two Views When Spacing Is Applied In Between
     Spacer(minLength: 0)
              
     //.....SOME VIEWS.....
              
     Divider()
  }
          
        

Presentations


Alert

This is used to create an Alert presentation
Syntax

init(title: Text, message: Text?, dismissButton: Alert.Button?)

Usage

          
  @State var showAlert = false
            
  VStack{
    //....Some View......//
  }
  .alert(isPresented: $showAlert) {
    // Alert View....
    Alert(title: Text("TITLE"),message: Text("MESSAGE"), primaryButton: .default(Text("ACTION 1"),action: {
       // Todo For Action 1
    }), secondaryButton: .destructive(Text("ACTION 2"),action: {
      // Todo For Action 2
    }))
  }
          
        

ActionSheet

It is a set of one or more actions which is presented in an alert format allowing user to choose from them.
Syntax

init(title: Text, message: Text?, buttons: [ActionSheet.Button])

Usage

          
  @State var showActionAlert = false

  VStack{
     //....Some View......//
  }
  .actionSheet(isPresented: $showActionAlert) {
    // Action Sheet...
    ActionSheet(title: Text("TITLE"), message: Text("MESSAGE"), buttons: [
      // Todo Implement Action Buttons...
      .default(Text("ACTION 1"), action: {})
    ])
  }
          
        

Sheets

SwiftUI’s sheets are used to present new view controllers modally over existing ones.
Syntax

sheet(isPresented: Binding, onDismiss: (() -> Void)? = nil, 
content: @escaping () -> Content) -> some View

Usage

                   
  @State var showPresentation = false
            
  VStack{
    //....Some View......//
  }
  .sheet(isPresented: $showPresentation) {
    // New View Will Be Presented...
    Text("New View")
  }
          
        

UIKit Integrations


UIViewRepresentable

This is a wrapper for a UIKit view that is used to integrate that view into the SwiftUI view hierarchy.
Syntax

func makeUIView(context: Self.Context) -> Self.UIViewType

Usage

          
  struct UIKitView: UIViewRepresentable {
    
    func makeUIView(context: Context) -> UIView {
      // Decalre Your UIView Here....
      let uiview = UIView()
      uiview.backgroundColor = .red
                  
      return uiview
    }
              
    func updateUIView(_ uiView: UIView, context: Context) {
      // Update Your UIView When Any Changes Made...
    }
  }
          
        

UIViewControllerRepresentable

This is a view which represents a UIKit view controller.
Syntax

func makeUIViewController(context: Self.Context) -> Self.UIViewControllerType

In this Example We Created a UIImagePicker Controller From UIKit To SwiftUI View.

Usage

          
  struct UIKitViewController: UIViewControllerRepresentable {

    func makeUIViewController(context: Context) -> UIImagePickerController {

      // Declare Your UIViewController Here...
      let controller = UIImagePickerController()
      controller.sourceType = .photoLibrary
      // Assigning Delegate
      controller.delegate = context.coordinator
      return controller
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
      // Update Your UIViewController When Any Changes Made...
    }
    
    // When You Want to Use ViewController Delegate Methods....
    class Coordinator: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
        
      // Use Delegate Methods Here....
      func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
      }
    }
    
    func makeCoordinator() -> Coordinator {
      return UIKitViewController.Coordinator()
    }
  }
          
        

UIApplicationDelegateAdaptor

This is a property wrapper which is used in App to provide a UIApplicationDelegate Protocols And Methods from UIKit to SwiftUI Life Cycle.
Syntax

init(DelegateType.Type)

Usage

          
 @main
 struct BeginnersCourse: App {
   @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
   var body: some Scene {
      WindowGroup {
        ContentView()
      }
    }
  }
            
 class AppDelegate: NSObject,UIApplicationDelegate{
    // UIApplication Delegate Methods.....
  }