Author: saqibkhan

  • SwiftUI Navigation Toolbar & Bar Items

    Basic toolbar

    Add leading and trailing bar buttons using .toolbar with ToolbarItem placements.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ToolbarBasicDemo: View {
      var body: some View {
    
    NavigationStack {
      Text("Content")
        .navigationTitle("Toolbar")
        .toolbar {
          ToolbarItem(placement: .navigationBarLeading) { Button("Cancel") {} }
          ToolbarItem(placement: .navigationBarTrailing) { Button("Add") {} }
        }
    }
    } }

    In the example above, the .toolbar modifier adds a leading Cancel and trailing Add button.



    Placements

    Place items at the bottom bar or show keyboard-anchored actions.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ToolbarPlacementsDemo: View {
      @State private var text = ""
      var body: some View {
    
    NavigationStack {
      VStack(spacing: 12) {
        TextField("Type...", text: $text).textFieldStyle(.roundedBorder)
      }
      .padding()
      .navigationTitle("Placements")
      .toolbar {
        ToolbarItem(placement: .bottomBar) { Button("Edit") {} }
        ToolbarItemGroup(placement: .keyboard) { Spacer(); Button("Done") { } }
      }
    }
    } }
  • SwiftUI Navigation navigationDestination

    SwiftUI Navigation: navigationDestination

    Define typed destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).


    Typed destinations

    Typed destinations allow you to define destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct NumberDetail: View { let n: Int; var body: some View { Text("Number: \(n)") } }
    struct TextDetail: View { let s: String; var body: some View { Text("Text: \(s)") } }
    
    struct DestinationTypedDemo: View {
      @State private var intPath: [Int] = []
      @State private var stringPath: [String] = []
      var body: some View {
    
    NavigationStack(path: $intPath) {
      VStack(spacing: 12) {
        Button("Push Int 7") { intPath.append(7) }
        NavigationLink("Push Text 'Hi'", value: "Hi")
      }
      .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
      .navigationDestination(for: String.self) { s in TextDetail(s: s) }
      .navigationTitle("Typed Destinations")
    }
    } }

    In the example above, the NumberDetail and TextDetail views are used as destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).



    Enum-based routing

    Enum-based routing allows you to define destinations for values pushed onto a NavigationStack path using .navigationDestination(for:).

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    enum Route: Hashable { case number(Int), text(String) }
    
    struct DestinationMultiDemo: View {
      @State private var path: [Route] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      VStack(spacing: 12) {
        Button("Go to number 5") { path.append(.number(5)) }
        Button("Go to text 'Hello'") { path.append(.text("Hello")) }
      }
      .navigationDestination(for: Route.self) { r in
        switch r {
        case .number(let n): Text("Number: \(n)")
        case .text(let s): Text("Text: \(s)")
        }
      }
      .navigationTitle("Enum Destinations")
    }
    } }
  • SwiftUI Navigation Programmatic Navigation

    SwiftUI Navigation: Programmatic Navigation

    Control navigation in code using NavigationPath and typed destinations.


    Path controls

    NavigationPath controls the navigation path.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct NumberDetail: View { let n: Int; var body: some View { Text("Number: \(n)") } }
    
    struct ProgrammaticPathDemo: 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() } }
      }
      .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
      .navigationTitle("Programmatic")
    }
    } }

    In the example above, the NavigationPath is used to control the navigation path.



    Reset & multi-push

    Reset the path and push multiple destinations.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ResetMultiPushDemo: View {
      @State private var path: [Int] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      VStack(spacing: 12) {
        Button("Reset to root") { path.removeAll() }
        Button("Go to 1 → 2 → 3") { path.append(contentsOf: [1,2,3]) }
      }
      .navigationDestination(for: Int.self) { n in Text("Screen #\(n)") }
      .navigationTitle("Reset & Multi-Push")
    }
    } }
  • SwiftUI Navigation Deep Links

    SwiftUI Navigation: Deep Links

    Handle incoming URLs to navigate directly to content using onOpenURL.


    Basic onOpenURL

    onOpenURL is used to handle incoming URLs.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ItemDetail: View { let id: Int; var body: some View { Text("Item #\(id)") } }
    
    struct DeepLinkBasicDemo: View {
      @State private var path: [Int] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      Text("Home")
        .onOpenURL { url in
          if url.scheme == "myapp", url.host == "item", let id = Int(url.lastPathComponent) {
            path.append(id)
          }
        }
        .navigationDestination(for: Int.self) { id in ItemDetail(id: id) }
        .navigationTitle("Deep Links")
    }
    } }

    In the example above, the onOpenURL modifier is used to handle incoming URLs.



    Route mapping

    Handle multiple hosts and route to different destinations.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct ProfileView: View { let user: String; var body: some View { Text("Profile: \(user)") } }
    struct ArticleView: View { let slug: String; var body: some View { Text("Article: \(slug)") } }
    
    enum Route: Hashable { case item(Int), profile(String), article(String) }
    
    struct DeepLinkRoutesDemo: View {
      @State private var path: [Route] = []
      var body: some View {
    
    NavigationStack(path: $path) {
      Text("Home")
        .onOpenURL { url in
          guard url.scheme == "myapp" else { return }
          switch url.host {
          case "item": if let id = Int(url.lastPathComponent) { path.append(.item(id)) }
          case "profile": path.append(.profile(url.lastPathComponent))
          case "article": path.append(.article(url.lastPathComponent))
          default: break
          }
        }
        .navigationDestination(for: Route.self) { route in
          switch route {
          case .item(let id): Text("Item #\(id)")
          case .profile(let u): ProfileView(user: u)
          case .article(let s): ArticleView(slug: s)
          }
        }
        .navigationTitle("Routes")
    }
    } }
  • SwiftUI Navigation Sheets & Popovers

    SwiftUI Navigation: Sheets & Popovers

    Present modals using .sheet.fullScreenCover, and popovers.


    Basic Sheet

    Present a modal using .sheet.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct SheetsBasicDemo: View {
      @State private var show = false
      var body: some View {
    
    Button("Show Sheet") { show = true }
      .sheet(isPresented: $show) {
        VStack(spacing: 12) {
          Text("Modal")
          Button("Close") { show = false }
        }
        .padding()
      }
    } }

    In the example above, the .sheet modifier is used to present a modal.



    Full Screen Cover

    Present a full screen modal using .fullScreenCover.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct FullScreenCoverDemo: View {
      @State private var show = false
      var body: some View {
    
    Button("Present Full Screen") { show = true }
      .fullScreenCover(isPresented: $show) {
        CoverView(onClose: { show = false })
      }
    } } struct CoverView: View { let onClose: () -> Void var body: some View {
    ZStack {
      Color.black.opacity(0.85).ignoresSafeArea()
      VStack(spacing: 12) {
        Text("Full Screen").foregroundStyle(.white)
        Button("Dismiss") { onClose() }
          .tint(.white)
      }
      .padding()
    }
    } }
  • SwiftUI Navigation TabView

    SwiftUI Navigation: TabView

    Switch between sections with TabView and .tabItem.


    Basic TabView

    Use TabView to switch between sections.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct TabBasicDemo: View {
      var body: some View {
    
    TabView {
      Text("Home").tabItem { Label("Home", systemImage: "house") }
      Text("Settings").tabItem { Label("Settings", systemImage: "gear") }
    }
    } }

    In the example above, the TabView is used to switch between sections.



    Selection & Badges

    Track the active tab with @State and add .badge().

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    enum Tab: Hashable { case home, inbox }
    
    struct TabSelectionDemo: View {
      @State private var selection: Tab = .home
      var body: some View {
    
    TabView(selection: $selection) {
      Text("Home").tabItem { Label("Home", systemImage: "house") }.tag(Tab.home)
      Text("Inbox").tabItem { Label("Inbox", systemImage: "tray") }.badge(3).tag(Tab.inbox)
    }
    } }
  • SwiftUI Navigation NavigationLink

    SwiftUI Navigation: NavigationLink

    Use NavigationLink to push a destination view when tapped.


    Basic destination

    The basic NavigationLink is used to push a destination view when tapped.

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct Detail: View { var body: some View { Text("Detail") } }
    
    struct NavLinkBasicDemo: View {
      var body: some View {
    
    NavigationStack {
      NavigationLink("Go to Detail", destination: Detail())
        .navigationTitle("Home")
    }
    } }

    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.



    Value-based link

    The value-based NavigationLink is used to push a destination view when tapped.

    Use NavigationLink(value:) with a typed navigationDestination(for:).

    Example

    Demo.swift

    ContentView.swift

    App.swift

    import SwiftUI
    
    struct NumberDetail: View { let n: Int; var body: some View { Text("Number: \(n)") } }
    
    struct NavLinkValueDemo: View {
      var body: some View {
    
    NavigationStack {
      VStack(spacing: 12) {
        NavigationLink("Go to 99", value: 99)
      }
      .navigationDestination(for: Int.self) { n in NumberDetail(n: n) }
      .navigationTitle("Value Links")
    }
    } }
  • 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()
    }
    } }