ViewLab

Swift & SwiftUI course › Session 3

SwiftUI fundamentals

How a SwiftUI app is put together: the App and its scenes, views as small structs, modifiers and why their order matters, stacks, frames, conditional views, ForEach and lazy grids.

About 20 minutes · covers App structure, views, modifiers, stacks and layout, dynamic views, ForEach

Open the interactive lesson (live previews, quizzes) →

What you'll learn

Contents

  1. App structure
  2. Views, body and some View
  3. Text, Image and SF Symbols
  4. Stacks, Spacer and Divider
  5. Padding, frame, background and overlay
  6. Modifier order
  7. ViewBuilder, conditions and Group
  8. ForEach
  9. ScrollView, lazy stacks and grids
  10. Safe area, Color, gradients and pinning
  11. offset vs padding vs position
  12. Old vs current modifiers, and colour scheme
  13. Common student mistakes
  14. Previews

App structure

A SwiftUI app is a struct that conforms to App. Its body returns one or more scenes. On iPhone and iPad, the scene is almost always a WindowGroup, and its content is your first view.

MyApp.swift and ContentView.swift from a new Xcode project (iOS App, SwiftUI interface).
import SwiftUI

@main                                  // the program's entry point: there is no main.swift
struct NotesApp: App {
    var body: some Scene {
        WindowGroup {                  // a scene: one window on iPhone, many on iPad and Mac
            ContentView()              // the root view
        }
    }
}

struct ContentView: View {
    var body: some View {
        Text("Hello, SwiftUI!")
    }
}

#Preview {
    ContentView()
}
PieceProtocol / typeJob
@mainAttributeMarks the type whose main() starts the app. Only one per app
NotesAppAppDescribes the app; its body is some Scene
WindowGroupSceneCreates windows showing the same view hierarchy
ContentViewViewDescribes a piece of UI; its body is some View
#PreviewMacro (Xcode 15+)Shows the view in Xcode's canvas. Older code uses a PreviewProvider struct

Try “App structure” with live code →

Views, body and some View

The View protocol has one requirement: a computed property body that returns another view. A view is a description of UI, not the UI itself. SwiftUI calls body whenever the data a view depends on changes, compares the result with the last one, and updates only what changed on screen.

Why some View?

Every modifier wraps the view in a new generic type, so the real type of a body is long, like ModifiedContent<ModifiedContent<Text, _PaddingLayout>, _BackgroundStyleModifier<Color>>. some View is an opaque type: the compiler knows the exact type (fast, statically checked) but you don't have to write it. It also means body must always return one concrete type.

body is implicitly @ViewBuilder; your own helper functions are not unless you mark them.
struct Badge: View {
    let isNew: Bool

    var body: some View {          // OK: inside body, if/else is built by @ViewBuilder
        if isNew {
            Text("NEW")
        } else {
            Image(systemName: "checkmark")
        }
    }

    func icon() -> some View {     // error: no @ViewBuilder here, and the two
        if isNew {                 // returns have different types (Text vs Image)
            return Text("NEW")
        }
        return Image(systemName: "checkmark")
    }

    @ViewBuilder                   // fix: let the result builder combine the branches
    func fixedIcon() -> some View {
        if isNew { Text("NEW") } else { Image(systemName: "checkmark") }
    }
}

Try “Views, body and some View” with live code →

Text, Image and SF Symbols

Common text and image modifiers.
VStack(spacing: 8) {
    Text("Swift Exam Prep")
        .font(.largeTitle)
        .fontWeight(.bold)
        .foregroundStyle(.blue)

    Text("A long description that may need to wrap onto several lines on a small phone.")
        .font(.body)
        .foregroundStyle(.secondary)
        .multilineTextAlignment(.center)
        .lineLimit(2)

    Text("Due Friday").font(.caption).italic()

    Image(systemName: "star.fill")          // an SF Symbol
        .font(.title)                       // symbols scale with the font
        .foregroundStyle(.yellow)

    Image("campus")                         // from Assets.xcassets
        .resizable()                        // must come first: it's an Image-only modifier
        .scaledToFit()                      // keep the aspect ratio
        .frame(width: 200)
        .clipShape(RoundedRectangle(cornerRadius: 12))

    Label("Settings", systemImage: "gear")  // icon + title together
}
ModifierEffect
.font(.title)Dynamic Type text style: .largeTitle, .title, .headline, .body, .caption…; scales with the user's text size setting
.font(.system(size: 24))Fixed point size (doesn't respect the text size setting unless you scale it)
.fontWeight(.semibold) / .bold()Weight
.foregroundStyle(.red)Text and symbol colour (iOS 15+). Replaces the older .foregroundColor
.multilineTextAlignment(.center)Alignment of wrapped lines
.lineLimit(2)Maximum lines, then …
.resizable()Lets an image be resized; without it an image keeps its own pixel size
.scaledToFit() / .scaledToFill()Keep aspect ratio: fit inside, or fill and overflow (clip it)

Try “Text, Image and SF Symbols” with live code →

Stacks, Spacer and Divider

Stacks arrange child views: VStack vertically, HStack horizontally, ZStack on top of each other (later children in front). Each takes an alignment and (except ZStack) a spacing.

A row with Spacer, and a ZStack card.
VStack(alignment: .leading, spacing: 12) {
    HStack {
        Image(systemName: "person.circle.fill")
            .font(.largeTitle)
        VStack(alignment: .leading) {
            Text("Asha").font(.headline)
            Text("iOS Developer").foregroundStyle(.secondary)
        }
        Spacer()                              // pushes the badge to the right edge
        Text("PRO")
            .font(.caption.bold())
            .padding(6)
            .background(.orange, in: Capsule())
    }
    Divider()                                 // a thin line across the stack
    ZStack(alignment: .bottomTrailing) {
        RoundedRectangle(cornerRadius: 16)
            .fill(.blue)
            .frame(height: 120)
        Text("Front: drawn last")
            .foregroundStyle(.white)
            .padding()
    }
}
.padding()
StackDirectionalignment: typeValues
VStackTop to bottomHorizontalAlignment.leading, .center (default), .trailing
HStackLeading to trailingVerticalAlignment.top, .center (default), .bottom, .firstTextBaseline
ZStackBack to frontAlignment.center (default), .topLeading, .bottomTrailing…

Try “Stacks, Spacer and Divider” with live code →

Padding, frame, background and overlay

Layout modifiers.
Text("Padding")
    .padding()                      // system default amount on all sides
    .padding(.horizontal, 24)       // only leading and trailing
    .padding(.top, 8)

Text("Fixed frame")
    .frame(width: 200, height: 60)  // a 200 x 60 box; the text is centred in it

Text("Full width, left aligned")
    .frame(maxWidth: .infinity, alignment: .leading)   // as wide as the parent allows

Text("Card")
    .padding()
    .background(.yellow)                                  // fills the view's bounds
    .overlay(alignment: .topTrailing) {                   // drawn on top, same bounds
        Circle().fill(.red).frame(width: 12, height: 12)
    }

Text("Rounded")
    .padding()
    .background(.blue, in: RoundedRectangle(cornerRadius: 12))
    .foregroundStyle(.white)
ModifierWhat it really does
.padding()Wraps the view in a slightly bigger view with empty space around it
.frame(width:height:)Wraps the view in an invisible box of that size and places the view inside (centred by default)
.frame(maxWidth: .infinity)The box grows to the full width offered by the parent
.background(...)Draws something behind the view, sized to the view's bounds
.overlay(...)Draws something in front of the view, sized to its bounds
.foregroundStyle(...)Sets the colour or style for content inside, such as text and symbols

Try “Padding, frame, background and overlay” with live code →

Modifier order

Each modifier wraps the view it's called on and returns a new view. So the order of modifiers is the order of wrapping, and changing it changes the result. This is a favourite exam and interview question.

Same modifiers, different order, different screens.
Text("A")
    .padding()
    .background(.blue)      // blue covers the text AND the padding: a big blue box

Text("B")
    .background(.blue)      // blue hugs the text only
    .padding()              // then transparent space is added outside the blue

Text("C")
    .frame(width: 200, height: 80)
    .background(.yellow)    // yellow fills the whole 200 x 80 frame

Text("D")
    .background(.yellow)    // yellow is behind the text only...
    .frame(width: 200, height: 80)   // ...then the text sits in a clear 200 x 80 box

You can see the wrapping in plain Swift. Below is a tiny model of SwiftUI: each modifier returns a wrapper struct that holds the view it modified, just like ModifiedContent does.

protocol View {
    var width: Int { get }
    var tree: String { get }
}
struct Text: View {
    let width: Int
    var tree: String { "Text" }
}
struct Padding<Content: View>: View {
    let content: Content
    let amount: Int
    var width: Int { content.width + 2 * amount }
    var tree: String { "padding(\(amount)) <- \(content.tree)" }
}
struct Background<Content: View>: View {
    let content: Content
    let color: String
    var width: Int { content.width }               // a background never changes the size
    var tree: String { "background(\(color)) <- \(content.tree)" }
}
extension View {
    func padding(_ amount: Int = 16) -> Padding<Self> { Padding(content: self, amount: amount) }
    func background(_ color: String) -> Background<Self> { Background(content: self, color: color) }
}

let a = Text(width: 40).padding().background("blue")
let b = Text(width: 40).background("blue").padding()
print(a.tree)
print(b.tree)
print("blue area:", a.width, "vs", b.content.width)
print("total width:", a.width, "vs", b.width)

Output

background(blue) <- padding(16) <- Text
padding(16) <- background(blue) <- Text
blue area: 72 vs 40
total width: 72 vs 72
What does this print?
protocol View { var width: Int { get } }
struct Text: View { let width: Int }
struct Padding<Content: View>: View {
    let content: Content
    var width: Int { content.width + 20 }
}
struct Frame<Content: View>: View {
    let content: Content
    let fixed: Int
    var width: Int { fixed }
}
extension View {
    func padding() -> Padding<Self> { Padding(content: self) }
    func frame(width: Int) -> Frame<Self> { Frame(content: self, fixed: width) }
}
print(Text(width: 50).padding().frame(width: 100).width)
print(Text(width: 50).frame(width: 100).padding().width)
Show the answer
100
120

Try “Modifier order” with live code →

ViewBuilder, conditions and Group

body and the content closures of stacks are @ViewBuilder closures: a result builder that turns a list of views, if/else and switch into one combined view. You can't put arbitrary statements (like a for loop or print) in them; use ForEach for repetition.

if/else adds or removes a view; a ternary changes a modifier's value.
struct StatusRow: View {
    let name: String
    let isOnline: Bool
    let unread: Int

    var body: some View {
        HStack {
            Text(name)
            Spacer()
            if unread > 0 {                                   // view appears or disappears
                Text("\(unread)")
                    .font(.caption.bold())
                    .padding(6)
                    .background(.red, in: Circle())
                    .foregroundStyle(.white)
            }
            Circle()
                .fill(isOnline ? Color.green : Color.gray)  // same view, different value
                .frame(width: 10, height: 10)
        }
        .opacity(isOnline ? 1 : 0.5)
    }
}
if/else in a builderTernary in a modifier
Two different views (SwiftUI stores a _ConditionalContent)One view whose property changes
Switching branches removes one view and inserts another: its state resets, and it transitions in and outThe view keeps its identity and state; the change can animate smoothly
Use to show or hide whole piecesUse for colours, sizes, opacity, offsets

Since body is just a computed property, a view is a function of its data: same input, same output. Plain Swift shows the idea.

What does this print?
struct UnreadBadge {
    let count: Int
    var body: String {
        if count == 0 { return "" }
        return count > 99 ? "99+" : "\(count)"
    }
}
for n in [0, 7, 250] {
    print("[" + UnreadBadge(count: n).body + "]")
}
Show the answer
[]
[7]
[99+]

Group

Group has no layout of its own: the children are laid out by the parent stack.
Group {
    Text("Name")
    Text("Email")
    Text("Phone")
}
.font(.headline)            // applied to each child
.foregroundStyle(.blue)

Try “ViewBuilder, conditions and Group” with live code →

ForEach

ForEach creates one view per element of a collection. It's a view, not a loop: it needs to tell the elements apart between updates, so each one needs a stable, unique identity.

The three ways to give ForEach identity.
// 1. A constant range of Int
ForEach(0..<3) { i in
    Text("Row \(i)")
}

// 2. Values that are Hashable, using the value itself as the id
let subjects = ["Maths", "Physics", "Swift"]
ForEach(subjects, id: \.self) { subject in
    Text(subject)
}

// 3. Identifiable elements: no id: needed
struct Student: Identifiable {
    let id: Int
    let name: String
}
let students = [Student(id: 1, name: "Asha"), Student(id: 2, name: "Ravi")]
ForEach(students) { student in
    Text(student.name)
}
FormElements mustWatch out for
ForEach(0..<n)Be a Range<Int>The range should be constant; for a changing count, use ForEach(0..<n, id: \.self) or real data
ForEach(items, id: \.self)Be HashableDuplicate values produce duplicate ids: rows get mixed up
ForEach(items, id: \.code)Have a Hashable propertyThat property must be unique
ForEach(items)Be IdentifiableThe id must stay the same for the same item

Here is the idea behind ForEach in plain Swift: every element must produce a Hashable id, and duplicate ids are a problem. id: \.self is like passing { $0 }, and Identifiable supplies { $0.id }.

func forEachRow<Item, ID: Hashable>(_ items: [Item], id: (Item) -> ID, row: (Item) -> String) {
    var seen = Set<ID>()
    for item in items {
        let key = id(item)
        if !seen.insert(key).inserted {
            print("warning: duplicate id \(key)")
        }
        print(row(item))
    }
}
func forEachRow<Item: Identifiable>(_ items: [Item], row: (Item) -> String) {
    forEachRow(items, id: { $0.id }, row: row)     // Identifiable supplies the id
}

// Like ForEach(names, id: \.self): the value is the id
forEachRow(["Asha", "Ravi", "Asha"], id: { $0 }) { "Row \($0)" }

// Like ForEach(photos): unique ids, even with equal titles
struct Photo: Identifiable {
    let id: Int
    let title: String
}
forEachRow([Photo(id: 1, title: "Lake"), Photo(id: 2, title: "Lake")]) { "\($0.id): \($0.title)" }

Output

Row Asha
Row Ravi
warning: duplicate id Asha
Row Asha
1: Lake
2: Lake

Try “ForEach” with live code →

ScrollView, lazy stacks and grids

Stacks don't scroll. Wrap content in a ScrollView to scroll it. A plain VStack creates all its children at once; a lazy stack creates them only as they scroll into view, which matters for long lists.

Vertical and horizontal scrolling.
ScrollView {                                   // vertical by default
    LazyVStack(alignment: .leading, spacing: 12) {
        ForEach(1...1000, id: \.self) { n in
            Text("Item \(n)")                  // built only when near the screen
        }
    }
    .padding()
}

let colors: [Color] = [.red, .orange, .green, .blue, .purple]
ScrollView(.horizontal, showsIndicators: false) {
    LazyHStack {
        ForEach(colors, id: \.self) { color in
            RoundedRectangle(cornerRadius: 12)
                .fill(color)
                .frame(width: 120, height: 80)
        }
    }
}

LazyVGrid and GridItem

The columns array decides the grid.
let fixed    = [GridItem(.fixed(100)), GridItem(.fixed(100))]     // exactly 2 columns of 100 pt
let flexible = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())]  // 3 equal columns
let adaptive = [GridItem(.adaptive(minimum: 80))]                  // as many 80+ pt columns as fit

ScrollView {
    LazyVGrid(columns: adaptive, spacing: 12) {
        ForEach(photos) { photo in
            PhotoTile(photo: photo)
        }
    }
    .padding()
}
GridItem sizeColumnsWidth of each
.fixed(100)One per item in the arrayExactly 100 points
.flexible(minimum:maximum:)One per item in the arrayShare the space equally, within the limits
.adaptive(minimum: 80)As many as fit (one GridItem makes many columns)At least 80 points, stretched to fill
VStack / HStackLazyVStack / LazyHStackList
Creates childrenAll at onceAs they appearAs they appear (and reuses rows)
Scrolls by itselfNoNo: put it in a ScrollViewYes
StylingPlainPlainSystem list style, separators, swipe actions
Use forSmall, fixed layoutsLong custom feedsStandard table-style lists

Try “ScrollView, lazy stacks and grids” with live code →

Safe area, Color, gradients and pinning

The safe area is the part of the screen not covered by the status bar, the Dynamic Island or notch, and the home indicator. SwiftUI keeps your content inside it by default. .ignoresSafeArea() lets one view extend under those edges.

Color is a view

Color.orange is not only a value you pass to modifiers: it is a view that takes all the space it is offered. That is why a Color at the back of a ZStack fills the screen, and why Color.orange.ignoresSafeArea() reaches the very edges.

Only the background ignores the safe area; the content stays readable.
struct WelcomeScreen: View {
    var body: some View {
        ZStack {
            Color.orange                    // a view: fills the whole ZStack
                .ignoresSafeArea()          // and the area under the status bar and home indicator
            VStack(spacing: 12) {
                Image(systemName: "sparkles")
                    .font(.system(size: 60))
                Text("Welcome")
                    .font(.largeTitle.bold())
            }
            .foregroundStyle(.white)        // the text stays inside the safe area
        }
    }
}
CodeWhat it does
.ignoresSafeArea()Extends this view under every safe-area edge (iOS 14+)
.ignoresSafeArea(edges: .top)Only under the top edge
.ignoresSafeArea(.keyboard)Don't move up when the keyboard appears
.background(Color.mint.ignoresSafeArea())Background colour edge to edge, content inside the safe area

Gradients

A gradient is also a view that fills its space. LinearGradient blends colours along a line; RadialGradient blends outwards from a centre. For a quick one-colour gradient, Color.teal.gradient (iOS 16+) is a style you can pass to .fill or .background.

Gradients used as full-screen views and as a fill.
LinearGradient(colors: [.indigo, .cyan],
               startPoint: .top, endPoint: .bottom)      // top to bottom
    .ignoresSafeArea()

LinearGradient(colors: [.pink, .orange],
               startPoint: .topLeading, endPoint: .bottomTrailing)   // diagonal

RadialGradient(colors: [.yellow, .red],
               center: .center, startRadius: 10, endRadius: 200)     // from the centre outwards

Circle()
    .fill(Color.teal.gradient)                         // iOS 16+ one-colour gradient
    .frame(width: 80, height: 80)

Pinning with frame(maxWidth:maxHeight:alignment:)

frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom) makes an invisible box as large as the parent allows and puts the content at the bottom of it. It is the simplest way to pin something to an edge without a Spacer.

The title stays centred; the hint is pinned to the bottom (inside the safe area).
struct BadgeScreen: View {
    var body: some View {
        ZStack {
            LinearGradient(colors: [.purple, .blue], startPoint: .top, endPoint: .bottom)
                .ignoresSafeArea()

            Text("Level 4")
                .font(.title.bold())
                .foregroundStyle(.white)

            Text("Tap to continue")
                .padding()
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)
                .foregroundStyle(.white.opacity(0.8))
        }
    }
}
WantWrite
Fill the width, text on the left.frame(maxWidth: .infinity, alignment: .leading)
Fill the height, content at the bottom.frame(maxHeight: .infinity, alignment: .bottom)
Content in the top-right corner.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
VStack {
    Text("Hi")
}
.background(Color.green)

Try “Safe area, Color, gradients and pinning” with live code →

offset vs padding vs position

All three seem to "move" a view, but only padding changes layout. offset moves the drawing after layout, so the neighbours don't notice. position places the view's centre at a point in its parent's coordinate space, and the view then takes all the space offered.

offset changes where a view is drawn, not where it is laid out.
HStack(spacing: 8) {
    Rectangle().fill(.red).frame(width: 40, height: 40)
    Rectangle().fill(.green).frame(width: 40, height: 40)
        .offset(y: 30)                       // drawn 30 points lower; its slot stays where it was
    Rectangle().fill(.blue).frame(width: 40, height: 40)
}

Text("Badge")
    .padding(.leading, 30)                   // the view really grows: neighbours move

Text("Pinned")
    .position(x: 100, y: 50)                 // centre at (100, 50) inside the parent
ModifierMoves the view?Affects other views?Typical use
.padding(...)Adds space around itYes: it is bigger nowSpacing
.offset(x:y:)Shifts the drawingNo: the old slot staysSmall nudges, badges, animations
.position(x:y:)Puts its centre at a pointIt takes all the offered spaceAbsolute placement; rare in normal screens

A plain-Swift model of the difference: layout uses width, and only padded changes it.

What does this print?
struct Box {
    var width = 40
    var x = 0          // where it is drawn
    func padded(_ n: Int) -> Box { var b = self; b.width += 2 * n; return b }
    func offset(_ dx: Int) -> Box { var b = self; b.x += dx; return b }
}
let a = Box().offset(30)
let b = Box().padded(10)
print(a.width, a.x, b.width, b.x)
Show the answer
40 30 60 0
Three 40-point squares sit in an HStack. The middle one gets .offset(x: 60). What happens to the right-hand square?
Show the answer

Nothing: it stays where it was. The middle square is drawn 60 points to the right, on top of the right-hand one, and an empty gap is left in its old slot. With .padding(.leading, 60) instead, the right-hand square would move along too.

Try “offset vs padding vs position” with live code →

Old vs current modifiers, and colour scheme

Older tutorials (and a lot of lab code) use modifiers that are deprecated in recent SDKs. They still compile for iOS 17, sometimes with a warning, but write the current form in new code and in exams.

Older codeCurrent codeWhy
.foregroundColor(.red).foregroundStyle(.red)Takes any style: colours, gradients, .secondary
.cornerRadius(12) on a view.clipShape(.rect(cornerRadius: 12))Clipping to a shape is explicit. .rect(cornerRadius:) is iOS 17; before that write RoundedRectangle(cornerRadius: 12)
NavigationViewNavigationStackCovered in Session 6
Same look, current modifiers.
// Older style
Image(systemName: "star.fill")
    .padding()
    .background(Color.yellow)
    .cornerRadius(12)
    .foregroundColor(.orange)

// Current style (iOS 17)
Image(systemName: "star.fill")
    .padding()
    .background(.yellow)
    .clipShape(.rect(cornerRadius: 12))
    .foregroundStyle(.orange)

preferredColorScheme

.preferredColorScheme(.dark) asks the system to show the whole presentation (the window, or the sheet it is in) in dark mode, not just the view you put it on. Pass nil to follow the system setting again. To read the current scheme, use @Environment(\.colorScheme).

Read with @Environment, request with preferredColorScheme.
struct ThemeDemo: View {
    @Environment(\.colorScheme) private var scheme
    let forceDark: Bool

    var body: some View {
        Text(scheme == .dark ? "Dark" : "Light")
            .padding()
            .background(.background)                  // adapts to the scheme
            .preferredColorScheme(forceDark ? .dark : nil)
    }
}

Try “Old vs current modifiers, and colour scheme” with live code →

Common student mistakes

Several views in body with no container

This compiles, which surprises people:

No VStack, yet no error.
struct TwoLines: View {
    var body: some View {
        Text("First")
        Text("Second")
    }
}

It works only because the View protocol marks body as a @ViewBuilder. The builder combines the two Texts into one view (a TupleView), so body still returns one type. But that view adds no layout: it behaves like a Group, and the parent decides what happens. Inside a VStack the texts stack, inside an HStack they sit side by side, and inside a List each becomes its own row. A modifier on TwoLines() is applied to each Text separately.

navigationTitle with no NavigationStack

Compiles, runs, shows no title.
struct SettingsScreen: View {
    var body: some View {
        List {
            Text("Notifications")
            Text("Privacy")
        }
        .navigationTitle("Settings")      // no NavigationStack above it: nothing appears
    }
}

navigationTitle doesn't draw anything itself. It passes a title up to the nearest navigation container, which draws the bar. With no NavigationStack above it there is no bar, so the title is silently ignored. Wrap the screen (usually at the root) in NavigationStack { ... }.

SettingsScreen above is the root view in WindowGroup. Instead of editing the screen, you write NavigationStack { SettingsScreen() } in the app file. Does the title appear now?
Show the answer

Yes. The title only needs some NavigationStack above it, not one in the same file. The opposite mistake is also common: adding another NavigationStack inside a screen that was already pushed, which nests two stacks.

Goal: the gradient fills the whole screen, the discount is a white pill with red text, "Ends tonight" sits at the bottom, and the title "Offers" shows in a navigation bar.
import SwiftUI

struct OfferBanner: View {
    let title: String
    let discount: Int

    var body: some View {
        ZStack {
            LinearGradient(colors: [.orange, .red],
                           startPoint: .top, endPoint: .bottom)

            VStack(spacing: 8) {
                Text(title)
                    .font(.title.bold())
                Text("\(discount)% off")
                    .background(.white)                      // [A]
                    .padding(8)
                    .foregroundColor(.red)                   // [B]
            }
            .foregroundStyle(.white)
            .ignoresSafeArea()                               // [C]

            Text("Ends tonight")
                .frame(width: .infinity, alignment: .bottom) // [D]
        }
        .navigationTitle("Offers")                           // [E]
    }
}

#Preview {
    OfferBanner(title: "Monsoon sale", discount: 30)
}
Show the bugs
  • [A] .background(.white) comes before .padding(8), so the white only hugs the text and the padding outside it is clear. Fix: Swap them: .padding(8).background(.white, in: Capsule()).
  • [B] .foregroundColor is deprecated in recent SDKs. Fix: Use .foregroundStyle(.red).
  • [C] .ignoresSafeArea() is on the text stack, while the gradient (the thing that should reach the edges) still stops at the safe area. Fix: Remove it from the VStack and put .ignoresSafeArea() on the LinearGradient.
  • [D] width: .infinity is an invalid fixed width, and it can't pin anything vertically. Fix: .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom).
  • [E] Nothing encloses the view in a NavigationStack (the preview shows it alone), so the title never appears. Fix: Wrap it: NavigationStack { OfferBanner(...) } in the preview and in the app.

Try “Common student mistakes” with live code →

Previews

Each #Preview appears as a tab in the canvas.
#Preview {
    ProfileCard(profile: .sample)
        .padding()
}

#Preview("Dark mode") {
    ProfileCard(profile: .sample)
        .preferredColorScheme(.dark)
}

// Before Xcode 15:
struct ProfileCard_Previews: PreviewProvider {
    static var previews: some View {
        ProfileCard(profile: .sample)
    }
}

Try “Previews” with live code →

Exam traps

Code or claimWhat really happens
.padding().background(.blue)Blue covers the text and the padding
.background(.blue).padding()Blue hugs the text; the padding outside is clear
.frame(width: 200).background(.yellow)Yellow fills the 200-point box
.background(.yellow).frame(width: 200)Yellow only behind the text
VStack(alignment: .top)Compile error: a VStack takes a horizontal alignment
HStack(alignment: .leading)Compile error: an HStack takes a vertical alignment
Default stack spacingNot zero: a system value. Use spacing: 0
First child of a ZStackDrawn at the back
Image("x").frame(width: 50) without .resizable()The image keeps its own size
.frame(...).resizable()Compile error: resizable is only on Image
Returning Text or Image from a plain -> some View functionCompile error: add @ViewBuilder or use one type
if vs ternary for a colourif makes two views (state resets); a ternary keeps one view
print or a for loop inside bodyNot allowed in a ViewBuilder; use ForEach
ForEach(names, id: \.self) with duplicatesDuplicate identities: rows can get mixed up
ForEach(items) with no id:Elements must be Identifiable
LazyVGrid without a ScrollViewDoesn't scroll
GridItem(.adaptive(minimum: 80))One item, many columns: as many as fit
Spacer() in an HStackTakes all free horizontal space
Views are classesFalse: views are structs, rebuilt often
@main on two typesCompile error: one entry point per app
.ignoresSafeArea() on the VStack of textText can go under the status bar; put it on the background
.offset(x: 50)Moves the drawing only; neighbours don't move
.frame(width: .infinity)Invalid frame; use maxWidth: .infinity
.navigationTitle with no NavigationStack aboveCompiles, shows nothing
Two views in body, no containerCompiles (@ViewBuilder); the parent decides the layout
.preferredColorScheme(.dark) on one viewChanges the whole window or sheet
.cornerRadius(12) / .foregroundColor on a viewDeprecated in recent SDKs: .clipShape(.rect(cornerRadius: 12)) / .foregroundStyle

Viva questions and answers

What is the entry point of a SwiftUI app?

A struct marked @main that conforms to App. Its body returns scenes, usually a WindowGroup containing the root view.

What is a Scene?

A part of the app's UI the system manages, such as a window. WindowGroup is the scene used on iOS; on iPad and Mac it can create several windows.

What does the View protocol require?

One computed property, body, which returns another view. Built-in primitive views like Text end the chain.

Why are SwiftUI views structs?

They are lightweight value descriptions of UI. Creating and discarding them is cheap, so SwiftUI can recompute body often and diff the results.

Explain some View.

It's an opaque return type: body returns one specific type that conforms to View. The compiler knows the exact nested type; we don't have to write it.

Why does modifier order matter?

Each modifier wraps the current view in a new view. .padding().background(.blue) colours the padded view; .background(.blue).padding() colours only the text, then adds clear space.

How does SwiftUI layout work?

The parent proposes a size, the child chooses its own size, and the parent positions the child. Modifiers like frame and padding are views that take part in this.

What is the difference between frame(width:) and frame(maxWidth:)?

width fixes the box's width. maxWidth: .infinity lets the box grow to fill the space offered; you usually add an alignment to place the content.

What is @ViewBuilder?

A result builder that turns several views and if/switch statements into one view. body and stack content closures use it automatically.

if/else or ternary in a view: which one?

Use if to add or remove whole views. Use a ternary to change a modifier's value, because it keeps the same view identity, so state is kept and changes animate smoothly.

What does ForEach need?

A stable identity for each element: a constant Range<Int>, a Hashable key path with id:, or Identifiable elements.

Why not use the array index as an id?

Indexes change when items are inserted or deleted, so SwiftUI would match the wrong data to the wrong row and animate incorrectly.

VStack vs LazyVStack?

A VStack builds all children immediately. A LazyVStack, used inside a ScrollView, builds them as they approach the screen, saving memory and time for long content.

Explain the three GridItem sizes.

.fixed is an exact width. .flexible shares the space equally within limits. .adaptive(minimum:) fits as many columns of at least that width as possible.

What is the difference between overlay and background?

Both draw another view sized to the modified view. background draws it behind; overlay draws it in front.

How do you preview a view?

Add a #Preview { MyView() } block (Xcode 15+) and open the canvas. Older code uses a PreviewProvider with a static previews property.

What is the safe area, and how do you draw outside it?

The region not covered by the status bar, notch or Dynamic Island, and home indicator. Content stays inside it by default; .ignoresSafeArea() lets a view, usually a background colour or gradient, extend under those edges.

Why can a Color fill the whole screen?

Color is a view that accepts all the space its parent offers. At the back of a ZStack it fills the stack; with .ignoresSafeArea() it reaches the edges.

offset vs padding?

Padding makes the view bigger, so layout changes and neighbours move. Offset only moves where the view is drawn after layout; its original slot stays, so views can overlap.

Why doesn't navigationTitle show anything sometimes?

It only passes a title up to a navigation container. With no NavigationStack above the view there is no navigation bar to show it.

What replaces .cornerRadius and .foregroundColor?

.clipShape(.rect(cornerRadius:)) (iOS 17; RoundedRectangle before) and .foregroundStyle. The old ones are deprecated in recent SDKs but still compile.

Quiz

  1. What does WindowGroup conform to?

    Show the answer

    Scene

  2. What is the only requirement of the View protocol?

    Show the answer

    A body property

  3. Why is body declared as some View?

    Show the answer

    It hides the long concrete type while the compiler still knows it

  4. Which code gives a large blue box with the text inside, with blue under the padding too?

    Show the answer

    .padding().background(.blue)

    The background is applied after the padding, so it is the size of text plus padding.

  5. What does this print?

    Show the answer

    25

    Each padding wrapper adds 10 to what it wraps: 5 + 10 + 10.

  6. Which alignment can a VStack take?

    Show the answer

    .leading

    VStack aligns children horizontally: .leading, .center or .trailing.

  7. In a ZStack, which child is drawn in front?

    Show the answer

    The last

  8. What does Spacer() do inside an HStack?

    Show the answer

    Takes all available horizontal space

  9. How do you make a view as wide as its container and left-aligned?

    Show the answer

    .frame(maxWidth: .infinity, alignment: .leading)

  10. Why doesn't Image("logo").frame(width: 50, height: 50) shrink a large image?

    Show the answer

    It needs .resizable() first

  11. Which ForEach requires its elements to be Identifiable?

    Show the answer

    ForEach(items)

  12. What does id: \.self require of the elements?

    Show the answer

    Hashable

  13. Which GridItem creates as many columns as fit?

    Show the answer

    .adaptive(minimum: 80)

  14. What is the main difference between VStack and LazyVStack?

    Show the answer

    LazyVStack creates children only when they are about to appear

  15. Changing a colour with a ternary instead of if/else...

    Show the answer

    keeps the same view, so its state is kept and the change can animate

  16. What does Group do?

    Show the answer

    Groups views without adding layout, so modifiers apply to each child

  17. Which is true about SwiftUI views?

    Show the answer

    They are lightweight structs that SwiftUI recreates often

  18. What does #Preview need to compile?

    Show the answer

    Xcode 15 or later

    The #Preview macro arrived with Xcode 15 (Swift 5.9). Older projects use PreviewProvider.

  19. Which code colours the whole screen, including under the status bar, while keeping the text inside the safe area?

    Show the answer

    ZStack { Color.mint.ignoresSafeArea(); Text("Hi") }

    Only the Color ignores the safe area. On the ZStack, the text would be allowed under the edges too.

  20. The middle view of an HStack gets .offset(x: 40). What happens to the view after it?

    Show the answer

    It stays where it was

    offset is applied after layout; the original slot is kept.

  21. How do you pin a label to the bottom of the available space without a Spacer?

    Show the answer

    .frame(maxHeight: .infinity, alignment: .bottom)

  22. A screen has .navigationTitle("Home") but no NavigationStack anywhere above it. What happens?

    Show the answer

    It compiles and no title appears

  23. Why does a body containing two Text views with no stack compile?

    Show the answer

    body is a @ViewBuilder, which combines them into one view

    The builder makes one TupleView; the parent container decides the layout.

← Custom types and object-oriented Swift · State, bindings, controls and forms →

Practise this lesson interactively →