Category: 05. SwiftUI Basics

https://cdn3d.iconscout.com/3d/premium/thumb/ui-ux-3d-icon-png-download-9831982.png

  • SwiftUI Navigation NavigationStack

    SwiftUI Navigation: NavigationStack

    Use NavigationStack as the container for pushing and popping views.

    Use NavigationLink to create links that push views onto the stack.

    Use .navigationDestination to specify the view to display when a link is selected.


    NavigationStack Example

    Push and pop views using NavigationLink and .navigationDestination.

    Basic Stack Push

    Basic Stack Push is when you push a view onto the stack and pop it when you tap a button.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct Detail: View { let value: Int; var body: some View { Text("Detail: \(value)") } }
    
    struct NavStackBasicDemo: View {
      var body: some View {
    
    NavigationStack {
      List(1...5, id: \.self) { n in
        NavigationLink("Item \(n)", value: n)
      }
      .navigationDestination(for: Int.self) { n in Detail(value: n) }
      .navigationTitle("Items")
    }
    } }

    In the example above, the NavigationLink is used to push a view onto the stack and the .navigationDestination is used to specify the view to display when a link is selected.



    Programmatic Path

    Programmatic Path is when you push a view onto the stack and pop it when you tap a button.

    The difference between Basic Stack Push and Programmatic Path is that Programmatic Path uses a NavigationPath to manage the navigation state.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct NumberDetail: View { let n: Int; var body: some View { Text("Number: \(n)") } }
    
    struct NavStackPathDemo: View {
      @State private var path: [Int] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      VStack(spacing: 12) {
        Button("Go to 7") { path.append(7) }
        Button("Back") { if !path.isEmpty { _ = path.removeLast() } }
      }
      .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
      .navigationTitle("Path Demo")
    }
    } }
  • SwiftUI Navigation

    SwiftUI Navigation

    Learn to navigate with NavigationStack, push screens with NavigationLink, and present sheets and alerts.


    NavigationStack and NavigationLink

    Use NavigationStack with NavigationLink to push views onto a stack.

    Add titles and toolbar items.

    Syntax:

    • NavigationStack { List { NavigationLink("Title", destination: Detail()) } }
    • .navigationTitle("Title")
    • .toolbar { ... }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct Detail: View {
      let text: String
      var body: some View { Text(text).navigationTitle("Detail") }
    }
    
    struct NavStackDemo: View {
      var body: some View {
    
    NavigationStack {
      List(1...3, id: \.self) { i in
        NavigationLink("Item \(i)", destination: Detail(text: "Item \(i)"))
      }
      .navigationTitle("Items")
      .toolbar { ToolbarItem(placement: .navigationBarTrailing) { Button("Add") {} } }
    }
    } }

    This example builds a stack of items and pushes a Detail view when a row is tapped, with a title and a trailing toolbar button.


    Modal Presentation

    Present sheets with .sheet(isPresented:) and alerts with .alert.

    Syntax:

    • .sheet(isPresented: $flag) { View() }
    • .alert("Title", isPresented: $flag) { Buttons... } message: { Text("...") }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ModalDemo: View {
      @State private var showSheet = false
      @State private var showAlert = false
    
      var body: some View {
    
    VStack(spacing: 12) {
      Button("Show Sheet") { showSheet = true }
      Button("Show Alert") { showAlert = true }
    }
    .sheet(isPresented: $showSheet) {
      VStack(spacing: 12) {
        Text("Hello from a sheet!")
        Button("Close") { showSheet = false }
      }
      .padding()
      .presentationDetents([.medium])
    }
    .alert("Are you sure?", isPresented: $showAlert) {
      Button("Cancel", role: .cancel) { }
      Button("OK", role: .destructive) { }
    } message: {
      Text("This is a confirmation alert.")
    }
    .padding()
    } }

    This example toggles booleans to present a sheet and an alert; the sheet uses a medium detent and a simple close button.



    Programmatic Navigation (NavigationPath)

    Drive navigation in code by updating a NavigationPath or typed path binding.

    Syntax:

    • @State private var path: [T] = []
    • NavigationStack(path: $path) { ... }
    • .navigationDestination(for: T.self) { ... }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct NumberDetail: View {
      let n: Int
      var body: some View { Text("Number: \(n)") }
    }
    
    struct PathDemo: View {
      @State private var path: [Int] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      VStack(spacing: 12) {
        Button("Go to 42") { path.append(42) }
        Button("Back") { if !path.isEmpty { _ = path.removeLast() } }
      }
      .navigationTitle("Path Demo")
      .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
    }
    } }
  • SwiftUI Layout Lazy Stacks

    SwiftUI Layout: Lazy Stacks

    Use LazyVStack/LazyHStack to efficiently render large lists of views on demand.


    Lazy Stacks

    Lazy Stacks are used to efficiently render large lists of views on demand.

    Syntax:

    • LazyVStack { ForEach(...) { ... } }
    • LazyHStack { ForEach(...) { ... } }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct LazyStacksDemo: View {
      var body: some View {
    
    ScrollView {
      LazyVStack(spacing: 8) {
        ForEach(1...100, id: \.self) { i in
          Text("Row \(i)").frame(maxWidth: .infinity, alignment: .leading).padding(8)
            .background(.gray.opacity(0.1)).cornerRadius(6)
        }
      }.padding()
    }
    } }

    In the example above, the LazyVStack is used to efficiently render a large list of views on demand.



    Horizontal Lazy Stack

    Use LazyHStack inside a horizontal ScrollView for efficient carousels.

    Syntax:

    • ScrollView(.horizontal) { LazyHStack { ForEach(...) { ... } } }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct LazyHStackDemo: View {
      var body: some View {
    
    ScrollView(.horizontal) {
      LazyHStack(spacing: 12) {
        ForEach(1...50, id: \.self) { i in
          Text("Card \(i)")
            .padding(16)
            .background(.blue.opacity(0.1))
            .cornerRadius(8)
        }
      }.padding()
    }
    } }
  • SwiftUI Layout Safe Area

    SwiftUI Layout: Safe Area

    Control content under system bars with .ignoresSafeArea() and .safeAreaInset().


    Safe Area

    Use .ignoresSafeArea() to control content under system bars.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct SafeAreaDemo: View {
      var body: some View {
    
    ZStack {
      LinearGradient(colors: [.blue, .purple], startPoint: .top, endPoint: .bottom)
        .ignoresSafeArea()
      Text("Hello safe area")
        .padding()
        .background(.ultraThinMaterial)
        .cornerRadius(8)
    }
    } }

    In the example above, the .ignoresSafeArea() modifier is used to control content under system bars.



    Safe Area Insets

    Insert UI at the edges (like a toolbar) using .safeAreaInset.

    Syntax:

    • .safeAreaInset(edge: .bottom) { content }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct SafeAreaInsetDemo: View {
      var body: some View {
    
    ZStack {
      LinearGradient(colors: [.purple, .pink], startPoint: .top, endPoint: .bottom)
        .ignoresSafeArea()
      Text("Content").padding().background(.ultraThinMaterial, in: Capsule())
    }
    .safeAreaInset(edge: .bottom) {
      HStack {
        Image(systemName: "house.fill"); Spacer(); Image(systemName: "gear")
      }
      .padding()
      .background(.regularMaterial)
    }
    } }
  • SwiftUI Layout GeometryReader

    SwiftUI Layout: GeometryReader

    Read parent size and position to build responsive layouts with GeometryReader.


    GeometryReader

    Use GeometryReader to read parent size and position to build responsive layouts.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct GeometryDemo: View {
      var body: some View {
    
    GeometryReader { geo in
      VStack(spacing: 12) {
        Text("Width: \(Int(geo.size.width))")
        Text("Height: \(Int(geo.size.height))")
      }
      .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
    .background(.orange.opacity(0.1))
    } }


    Responsive Positioning

    Position elements based on container size using GeometryReaderalignment, and offset.

    Syntax:

    • GeometryReader { geo in ... }
    • .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
    • .offset(x: 0, y: -12)

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct GeometryPositionDemo: View {
      var body: some View {
    
    GeometryReader { geo in
      ZStack {
        Color.orange.opacity(0.1)
        Text("Bottom Right")
          .padding(8)
          .background(.thinMaterial, in: Capsule())
          .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
          .offset(x: 0, y: -12)
      }
    }
    } }
  • SwiftUI Layout Grids

    SwiftUI Layout: Grids

    Use LazyVGrid and LazyHGrid to arrange items in flexible grid layouts.


    Lazy Grids

    Lazy grids are used to display a large number of items in a grid layout.

    Syntax:

    • LazyVGrid(columns: columns, spacing: 12)
    • LazyHGrid(rows: rows, spacing: 12)

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct GridDemo: View {
      let columns = [GridItem(.flexible()), GridItem(.flexible())]
      var body: some View {
    
    LazyVGrid(columns: columns, spacing: 12) {
      ForEach(1...6, id: \.self) { i in
        Text("Item \(i)")
          .frame(maxWidth: .infinity)
          .padding(12)
          .background(.blue.opacity(0.1))
          .cornerRadius(8)
      }
    }.padding()
    } }

    In the example above, the grid is created using a LazyVGrid with two columns, each with a flexible width.



    Adaptive Grid

    Use adaptive columns to fit as many items per row as space allows.

    Syntax:

    • [GridItem(.adaptive(minimum: 100))]
    • LazyVGrid(columns: columns) { ... }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct AdaptiveGridDemo: View {
      let columns = [GridItem(.adaptive(minimum: 100), spacing: 12)]
      var body: some View {
    
    LazyVGrid(columns: columns, spacing: 12) {
      ForEach(1...12, id: \.self) { i in
        Text("Card \(i)")
          .frame(maxWidth: .infinity, minHeight: 60)
          .background(.green.opacity(0.12))
          .cornerRadius(8)
      }
    }
    .padding()
    } }
  • SwiftUI Layout Frames & Padding

    SwiftUI Layout: Frames & Padding

    Control size and layout using .frame() and spacing using .padding().


    Fixed Frames

    Use fixed width and height to size content.

    Syntax:

    • .frame(width: 160, height: 60)

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct FramesPaddingDemo: View {
      var body: some View {
    
    VStack(spacing: 16) {
      Text("Fixed size").frame(width: 160, height: 60).background(.blue.opacity(0.1))
      Text("Max width").frame(maxWidth: .infinity, alignment: .leading).padding(8).background(.green.opacity(0.1))
    }.padding()
    } }

    REMOVE ADS


    Flexible Frames and Alignment

    Use min/max constraints and alignment to size content responsively.

    Syntax:

    • .frame(minWidth: 120, maxWidth: .infinity, alignment: .trailing)
    • .frame(maxHeight: 120)

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct FlexibleFramesDemo: View {
      var body: some View {
    
    VStack(spacing: 12) {
      Text("Trailing")
        .frame(minWidth: 120, maxWidth: .infinity, alignment: .trailing)
        .padding(8)
        .background(.gray.opacity(0.1))
        .cornerRadius(6)
      Text("Tall block")
        .frame(maxWidth: .infinity)
        .frame(maxHeight: 120)
        .background(.orange.opacity(0.1))
        .cornerRadius(6)
    }
    .padding()
    } }
  • SwiftUI Layout Spacers & Alignment

    SwiftUI Layout: Spacers & Alignment

    Use Spacer() to distribute content and alignment parameters to control placement.


    Spacers

    Use Spacer() to distribute content and alignment parameters to control placement.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct SpacersAlignmentDemo: View {
      var body: some View {
    
    HStack {
      Text("Left"); Spacer(); Text("Right")
    }
    .frame(maxWidth: .infinity, alignment: .leading)
    .padding()
    } }


    Vertical Alignment and Guides

    Align text baselines and customize positioning with alignment and alignmentGuide.

    Syntax:

    • HStack(alignment: .firstTextBaseline) { ... }
    • .alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
    • VStack(alignment: .leading) { Spacer() }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct AlignmentGuideDemo: View {
      var body: some View {
    
    VStack(alignment: .leading, spacing: 16) {
      HStack(alignment: .firstTextBaseline, spacing: 8) {
        Text("Title").font(.title)
        Text("Aligned").alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
      }
      HStack {
        Text("Left"); Spacer(); Text("Right")
      }
    }
    .padding()
    } }
  • SwiftUI Layout Stacks

    SwiftUI Layout: Stacks

    Arrange views vertically, horizontally, or in layers using VStackHStack, and ZStack.


    Examples

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct StackDemo: View {
      var body: some View {
    
    VStack(spacing: 12) {
      Text("Title").font(.title)
      HStack {
        Text("Left")
        Spacer()
        Text("Right")
      }
      ZStack {
        Color.blue.opacity(0.1)
        Text("Overlay")
      }
    }.padding()
    } }


    Overlays and Alignment

    Layer content with ZStack and control placement using alignment and alignmentGuide.

    Syntax:

    • ZStack(alignment: .topLeading) { ... }
    • .alignmentGuide(.top) { d in d[.bottom] }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct OverlayDemo: View {
      var body: some View {
    
    ZStack(alignment: .topLeading) {
      Image(systemName: "rectangle.fill").resizable().foregroundStyle(.blue.opacity(0.15))
      Text("Badge")
        .padding(6)
        .background(.ultraThinMaterial, in: Capsule())
        .alignmentGuide(.top) { d in d[.bottom] } // custom guide
    }
    .frame(width: 220, height: 120)
    .padding()
    } }
  • SwiftUI Layout

    SwiftUI Layout

    Build flexible interfaces with stacks, frames, alignment, and spacing using SwiftUI’s layout system.


    Stacks and Spacing

    Use VStackHStack, and ZStack to arrange views vertically, horizontally, or in layers.

    Spacing and alignment are configurable.

    Syntax:

    • VStack(alignment: .leading, spacing: 8) { ... }
    • HStack { Text("A"); Spacer(); Text("B") }
    • ZStack { Color.blue; Text("Overlay") }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct StacksDemo: View {
      var body: some View {
    
    VStack(alignment: .leading, spacing: 12) {
      Text("Title").font(.title)
      HStack {
        Text("Left")
        Spacer()
        Text("Right")
      }
      ZStack {
        Color.blue.opacity(0.1)
        Text("Overlay")
      }
    }
    .padding()
    } }

    This example arranges content using vertical, horizontal, and layered stacks with titles, spacers, and padding.



    Frames and Alignment

    Adjust size and position with .frame().padding(), and .alignmentGuide.

    Syntax:

    • .frame(width: 200, height: 100)
    • .frame(maxWidth: .infinity, alignment: .leading)
    • .alignmentGuide(.firstTextBaseline) { d in d[.bottom] }

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct FrameDemo: View {
      var body: some View {
    
    VStack(spacing: 16) {
      ZStack(alignment: .topLeading) {
        Color.yellow.opacity(0.2)
        Text("Top Left").padding(6)
      }
      .frame(width: 200, height: 100) // fixed size
      HStack {
        Text("Left")
        Spacer()
        Text("Right")
      }
      .frame(maxWidth: .infinity, alignment: .leading) // expand horizontally
      HStack(alignment: .firstTextBaseline, spacing: 8) {
        Text("Title").font(.title)
        Text("Aligned baseline")
          .alignmentGuide(.firstTextBaseline) { d in d[.bottom] }
      }
    }
    .padding()
    } }