Drawing with SwiftUI
Apps as values: views, modifiers, and result builders; state and property wrappers; drawing on a Canvas; animating with tasks; handling taps and drags; and a model kept separate from its view, built around Conway’s Game of Life.
- CS61B
- For Project 0: Particle Simulator
- Swift book
- Properties · Opaque and Boxed Protocol Types
- Documentation
- SwiftUI tutorials · App · View · State · Canvas · TimelineView · Gesture
CS61B’s projects draw things: a falling-sand sandbox, a percolating grid, a chart of word histories, and a whole explorable world. CS61B uses a small Java drawing library for this. We will use SwiftUI, the framework Apple’s own apps are built with. This lesson covers the core of it, enough for the first project; Lessons 42 and 52 add data-driven screens and games.
The running example is Conway’s Game of Life: a grid of cells, each alive or dead, that changes in steps. A live cell with two or three live neighbors stays alive; a dead cell with exactly three live neighbors comes to life; every other cell is dead in the next step. From those rules come patterns that move, grow, and oscillate.
An app is a package
A SwiftUI app can be a Swift package, set up like Lesson 24’s, with one library for the model and one executable for the app:
Life/
├── Package.swift
├── Sources/
│ ├── LifeCore/Life.swift the model: plain Swift, no SwiftUI
│ └── LifeApp/LifeApp.swift the app: views and drawing
└── Tests/
└── LifeCoreTests/LifeTests.swift
// swift-tools-version: 6.4
import PackageDescription
let package = Package(
name: "Life",
platforms: [.macOS(.v27)],
targets: [
.target(name: "LifeCore"),
.executableTarget(name: "LifeApp", dependencies: ["LifeCore"]),
.testTarget(name: "LifeCoreTests", dependencies: ["LifeCore"]),
]
)
platforms sets the minimum system the package runs on. Without it,
the package manager assumes a very old macOS, and SwiftUI features newer
than that fail to compile unless every use is wrapped in an availability
check. .v27 needs swift-tools-version: 6.4 or later, which is also what
selects the Swift 6 language mode. The app’s entry point is a structure
marked @main that conforms to App:
import AppKit
import SwiftUI
@main
struct LifeApp: App {
init() {
// A command-line executable starts without a Dock icon or focus.
// These two lines make it behave like a normal Mac app.
NSApplication.shared.setActivationPolicy(.regular)
NSApplication.shared.activate()
}
var body: some Scene {
WindowGroup("Life") {
Text("Hello, Life")
.frame(width: 400, height: 300)
}
}
}
Run it with swift run LifeApp, or open Package.swift in Xcode, choose the
LifeApp scheme, and press Run. A window appears. Xcode also gives you
previews and a debugger for views, which is the usual way to work on
SwiftUI.
Views are values
A view is a structure that conforms to View by providing a body,
which is itself a view:
import SwiftUI
struct Badge: View {
let title: String
let count: Int
var body: some View {
HStack {
Text(title)
.font(.headline)
Text("\(count)")
.padding(6)
.background(.orange, in: Capsule())
}
}
}
Three ideas from earlier lessons do all the work:
- Views are values. A
Badgeis a small structure, cheap to create. It describes what should be on screen, rather than being the thing on screen. SwiftUI compares the descriptions from one moment to the next and updates only what changed. some Viewis an opaque type (Lesson 16): the body has one specific type, far too long to write out, andsome Viewsays “a type that conforms toView” without naming it.- Modifiers return new views.
.font(.headline)does not change the text; it wraps it in a new view that draws it with that font. The order matters:.paddingthen.backgroundputs the color behind the padding.
Result builders
The body of HStack { … } lists two views on separate lines with no commas
and no return, yet the closure produces a single value. That is a
result builder: a type that tells the compiler how to combine the
statements of a closure. SwiftUI’s is called ViewBuilder. The mechanism is
ordinary Swift, and a tiny builder of our own shows how it works:
@resultBuilder
struct LinesBuilder {
static func buildBlock(_ lines: String...) -> String {
lines.joined(separator: "\n")
}
}
func poem(@LinesBuilder _ content: () -> String) -> String {
content()
}
let text = poem {
"Roses are red,"
"structs are values,"
}
print(text)
// Roses are red,
// structs are values,
Each expression in the closure becomes an argument to buildBlock. A
ViewBuilder does the same with views, combining them into one view value.
Builders can also support if, switch, and for, which is why SwiftUI
code can show a view only when a condition holds.
State
A view describes the screen for the current data. When the data changes,
SwiftUI calls body again and updates the screen to match. Data that a view
owns and changes is marked @State:
import SwiftUI
struct Counter: View {
@State private var count = 0
@State private var step = 1
var body: some View {
VStack {
Text("Count: \(count)")
Stepper("Step: \(step)", value: $step, in: 1...10)
Button("Add") {
count += step
}
}
.padding()
}
}
Tapping the button changes count, and the text updates by itself. There is
no code that says “now change the label”: the label is always computed from
count.
Property wrappers
@State is a property wrapper: a type that controls how a property is
stored, with the attribute syntax as a shortcut. The Swift book’s chapter
on properties covers them; here is a small one that keeps a number within
bounds:
@propertyWrapper
struct Clamped {
private var value: Int
let range: ClosedRange<Int>
init(wrappedValue: Int, _ range: ClosedRange<Int>) {
self.range = range
value = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
var wrappedValue: Int {
get { value }
set { value = min(max(newValue, range.lowerBound), range.upperBound) }
}
}
struct Volume {
@Clamped(0...10) var level = 5
}
var volume = Volume()
volume.level += 20
print(volume.level) // 10
Writing @Clamped(0...10) var level = 5 makes Swift store a Clamped and
turn every use of level into its wrappedValue. @State works the same
way, except that its storage lives inside SwiftUI, which is why it survives
while the view structure itself is recreated again and again.
A wrapper can also offer a projected value, reached with $. For
@State, $step is a binding: a reference to the stored value that
another view can read and write. The Stepper above receives $step, not
step, because it needs to change it.
What would Swift print?
@propertyWrapper
struct Logged {
private var value = 0
private(set) var changes = 0
var wrappedValue: Int {
get { value }
set {
value = newValue
changes += 1
}
}
var projectedValue: Int { changes }
}
struct Score {
@Logged var points: Int
}
var score = Score()
score.points = 3
score.points += 4
print(score.points, score.$points)Show answer and explanation
Answer7 2
The wrapper counts assignments. score.points += 4 reads the value and
writes it once, so there are two changes in all. $points is the projected
value, which this wrapper defines to be the count.
The model comes first
Before drawing anything, write the Game of Life as plain Swift, with no SwiftUI at all. This is the part that can be tested, and the part that holds all the interesting logic:
struct Life: Equatable, CustomStringConvertible {
private(set) var cells: [[Bool]]
var rows: Int { cells.count }
var columns: Int { cells.first?.count ?? 0 }
/// A grid from rows of text: "#" is alive, anything else is dead.
init(_ picture: [String]) {
cells = picture.map { row in row.map { $0 == "#" } }
}
func isAlive(_ row: Int, _ column: Int) -> Bool {
(0..<rows).contains(row) && (0..<columns).contains(column) && cells[row][column]
}
func liveNeighbors(_ row: Int, _ column: Int) -> Int {
var count = 0
for dr in -1...1 {
for dc in -1...1 where (dr, dc) != (0, 0) && isAlive(row + dr, column + dc) {
count += 1
}
}
return count
}
mutating func step() {
cells = (0..<rows).map { row in
(0..<columns).map { column in
let n = liveNeighbors(row, column)
return n == 3 || (n == 2 && cells[row][column])
}
}
}
mutating func toggle(row: Int, column: Int) {
cells[row][column].toggle()
}
var description: String {
cells.map { row in String(row.map { $0 ? "#" : "." }) }.joined(separator: "\n")
}
}
var blinker = Life([".....", "..#..", "..#..", "..#..", "....."])
blinker.step()
print(blinker)
// .....
// .....
// .###.
// .....
// .....
step computes the whole next grid from the current one before replacing
it: every cell must see its neighbors as they were, not as they are being
updated. That is a common bug in simulations, and map building a new array
avoids it naturally.
In the package, this code goes in LifeCore with public added to the type,
its initializer, and the members the app uses (Lesson 24), and tests go in
LifeCoreTests.
What would Swift print?
var neighbors = 0
let grid = [[true, true, false], [false, true, false], [false, false, true]]
for dr in -1...1 {
for dc in -1...1 where (dr, dc) != (0, 0) {
let r = 1 + dr
let c = 1 + dc
if grid[r][c] {
neighbors += 1
}
}
}
print(neighbors)Show answer and explanation
Answer3
The center cell’s eight neighbors are everything except grid[1][1]: the
two live cells on the top row and the one in the bottom-right corner. The
center being alive does not count as its own neighbor.
Drawing on a Canvas
A Canvas view gives you a graphics context and the size of the area to
draw in. You describe shapes as Paths and fill or stroke them:
import SwiftUI
struct Grid: View {
let cells: [[Bool]]
var body: some View {
Canvas { context, size in
let rows = cells.count
let columns = cells.first?.count ?? 0
guard rows > 0, columns > 0 else { return }
let side = min(size.width / CGFloat(columns), size.height / CGFloat(rows))
for (row, line) in cells.enumerated() {
for (column, alive) in line.enumerated() {
let square = CGRect(x: CGFloat(column) * side, y: CGFloat(row) * side,
width: side, height: side)
context.fill(Path(square.insetBy(dx: 1, dy: 1)),
with: .color(alive ? .green : .gray.opacity(0.15)))
}
}
}
}
}
Screen coordinates start at the top-left corner, with y growing
downward, so row 0 is at the top. CGFloat and CGRect are the types
that drawing APIs use for measurements and rectangles. The cells are squares
of side side, chosen so the whole grid fits in whichever direction is
tighter.
A Canvas is fast because it draws directly, without making a view for each
cell. A few hundred views would also be fine, but a sandbox with a hundred
thousand particles needs drawing.
Time and input
The grid needs to advance on its own. A task attached to a view runs
while the view is on screen, and is cancelled when it goes away: the
structured concurrency of Lesson 22, managed by SwiftUI. With
.task(id: running), SwiftUI also cancels and restarts the task whenever
running changes:
.task(id: running) {
while running {
try? await Task.sleep(for: .seconds(1 / speed))
if running {
life.step()
}
}
}
Taps and drags come from gestures. A SpatialTapGesture reports where
the tap happened, in the view’s own coordinates, and the model needs a row
and column. The conversion is a pure function, so it can be tested without
any screen:
func cell(at point: (x: Double, y: Double), side: Double, rows: Int, columns: Int) -> (row: Int, column: Int)? {
guard point.x >= 0, point.y >= 0 else {
return nil
}
let row = Int(point.y / side)
let column = Int(point.x / side)
guard row < rows, column < columns else {
return nil
}
return (row, column)
}
print(cell(at: (x: 25, y: 5), side: 10, rows: 3, columns: 3)!) // (row: 0, column: 2)
print(cell(at: (x: 35, y: 5), side: 10, rows: 3, columns: 3) == nil) // true
Putting it together
Here is the whole view: the grid, taps that toggle cells, and controls to play, pause, step, and change speed.
import SwiftUI
struct Life {
private(set) var cells: [[Bool]]
var rows: Int { cells.count }
var columns: Int { cells.first?.count ?? 0 }
init(_ picture: [String]) { cells = picture.map { row in row.map { $0 == "#" } } }
mutating func step() { /* as above */ }
mutating func toggle(row: Int, column: Int) { cells[row][column].toggle() }
}
struct LifeView: View {
@State private var life = Life(["........", "..#.....", "...#....", ".###....",
"........", "........", "........", "........"])
@State private var running = false
@State private var speed = 5.0 // steps per second
var body: some View {
VStack(spacing: 12) {
GeometryReader { geometry in
let side = min(geometry.size.width / CGFloat(life.columns),
geometry.size.height / CGFloat(life.rows))
Canvas { context, _ in
for row in 0..<life.rows {
for column in 0..<life.columns {
let square = CGRect(x: CGFloat(column) * side, y: CGFloat(row) * side,
width: side, height: side)
context.fill(Path(square.insetBy(dx: 1, dy: 1)),
with: .color(life.cells[row][column] ? .green : .gray.opacity(0.15)))
}
}
}
.gesture(SpatialTapGesture().onEnded { tap in
let row = Int(tap.location.y / side)
let column = Int(tap.location.x / side)
if (0..<life.rows).contains(row), (0..<life.columns).contains(column) {
life.toggle(row: row, column: column)
}
})
}
.aspectRatio(1, contentMode: .fit)
GlassEffectContainer(spacing: 12) {
HStack(spacing: 12) {
Button(running ? "Pause" : "Play", systemImage: running ? "pause.fill" : "play.fill") {
running.toggle()
}
.buttonStyle(.glassProminent)
Button("Step", systemImage: "forward.frame.fill") { life.step() }
.buttonStyle(.glass)
.disabled(running)
Slider(value: $speed, in: 1...30) { Text("Speed") }
.frame(width: 140)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.glassEffect(.regular.interactive(), in: .capsule)
}
}
}
.padding()
.frame(minWidth: 400, minHeight: 460)
.task(id: running) {
while running {
try? await Task.sleep(for: .seconds(1 / speed))
if running {
life.step()
}
}
}
}
}
To run it, use LifeView() as the content of the WindowGroup in LifeApp.
(The Life here is abbreviated so the example stands alone; in the package,
the view imports the full model from LifeCore.)
Notice what the view does not do. It does not decide which cells live,
store its own copy of the grid, or redraw by hand. It reads the model, turns
input into calls on the model, and lets SwiftUI redraw whenever life
changes. That separation, a model that knows nothing about the screen and a
view that knows nothing about the rules, is how CS61B’s projects are
structured too, and it is why their tests can run without a window.
Liquid Glass
Since macOS 26, Apple’s platforms share a design language called Liquid
Glass: controls are drawn in a translucent material that bends and reflects
the content behind it, and reacts to the pointer. Standard controls, such as
toolbars, sidebars, menus, and sliders, adopt it automatically. For your own
controls, SwiftUI provides a few tools, all used in LifeView’s controls:
.buttonStyle(.glass)draws a button in glass;.buttonStyle(.glassProminent)makes it the tinted, prominent one, for the most important action (here, Play)..glassEffect(_:in:)puts any view on a glass shape.Glass.regularis the standard material;.clearis more transparent,.tint(_:)colors it, and.interactive()makes it respond to the pointer, as a control should.GlassEffectContainergroups nearby glass shapes so SwiftUI renders them together, which is faster and lets them interact: as shapes come close, their outlines blend and morph into one another. The container’sspacingsets how close is close; the larger it is, the sooner blending begins.
Apple’s design guidance is to use glass for the control layer, the
buttons and bars that float above the content, and never for the content
itself. In LifeView, the grid is the content and stays opaque; only the
controls are glass.
Put the lines in order
Put the lines in order so the program prints .##.
cells[i] || cells.indices.contains(i - 1) && cells[i - 1]print(String(cells.map { $0 ? "#" : "." }))}let next = cells.indices.map { i incells = nextvar cells = [false, true, false]
Show the correct program
var cells = [false, true, false]
let next = cells.indices.map { i in
cells[i] || cells.indices.contains(i - 1) && cells[i - 1]
}
cells = next
print(String(cells.map { $0 ? "#" : "." }))Lab 25: Drawing
The model problems run anywhere. The SwiftUI problems need a Mac; put the
view in the LifeApp target of the package from this lesson, and show it
from LifeApp’s WindowGroup.
Q0: What would Swift print?
What would Swift print?
@resultBuilder
struct SumBuilder {
static func buildBlock(_ parts: Int...) -> Int {
parts.reduce(0, +)
}
}
func total(@SumBuilder _ content: () -> Int) -> Int {
content()
}
let n = total {
1
20
300
}
print(n)Show answer and explanation
Answer321
Each line of the closure becomes one argument to buildBlock, which adds
them. A result builder decides what a list of statements means.
What would Swift print?
@propertyWrapper
struct Uppercase {
private var text = ""
var wrappedValue: String {
get { text }
set { text = newValue.uppercased() }
}
}
struct Sign {
@Uppercase var message: String
}
var sign = Sign()
sign.message = "open"
sign.message += " late"
print(sign.message)Show answer and explanation
AnswerOPEN LATE
Every assignment goes through the wrapper’s setter, including the one hidden
in +=, so the stored text is always uppercase.
Q1: A world without edges
Change Life so that the grid wraps around: the neighbor to the left of
column 0 is in the last column, and the neighbor above row 0 is in the last
row. Test it with a glider, which should return to its starting shape,
shifted one cell down and one to the right, every 4 steps, and should keep
going forever on a small grid.
Show solution
struct Life: Equatable, CustomStringConvertible {
private(set) var cells: [[Bool]]
var rows: Int { cells.count }
var columns: Int { cells.first?.count ?? 0 }
init(_ picture: [String]) {
cells = picture.map { row in row.map { $0 == "#" } }
}
func liveNeighbors(_ row: Int, _ column: Int) -> Int {
var count = 0
for dr in -1...1 {
for dc in -1...1 where (dr, dc) != (0, 0) {
let r = (row + dr + rows) % rows
let c = (column + dc + columns) % columns
if cells[r][c] {
count += 1
}
}
}
return count
}
mutating func step() {
cells = (0..<rows).map { row in
(0..<columns).map { column in
let n = liveNeighbors(row, column)
return n == 3 || (n == 2 && cells[row][column])
}
}
}
var description: String {
cells.map { row in String(row.map { $0 ? "#" : "." }) }.joined(separator: "\n")
}
}
let start = Life([".#...", "..#..", "###..", ".....", "....."])
var glider = start
for _ in 1...4 {
glider.step()
}
assert(glider == Life([".....", "..#..", "...#.", ".###.", "....."]))
for _ in 1...16 { // 20 steps in all: 5 cells down and 5 across, all the way around
glider.step()
}
assert(glider == start)Adding rows before taking % keeps the index non-negative: in Swift,
-1 % 5 is -1, not 4. After 20 steps the glider has moved 5 cells down and
5 right on a 5 by 5 grid, which brings it back exactly where it started.
Q2: From a point to a cell
Write cell(at:side:rows:columns:) as in this lesson, but for a grid that is
centered in a larger area: the grid is drawn starting at origin, not at
(0, 0). Return nil for points outside the grid, including points exactly on
its right or bottom edge.
Show solution
func cell(at point: (x: Double, y: Double), origin: (x: Double, y: Double),
side: Double, rows: Int, columns: Int) -> (row: Int, column: Int)? {
let x = point.x - origin.x
let y = point.y - origin.y
guard x >= 0, y >= 0 else {
return nil
}
let row = Int(y / side)
let column = Int(x / side)
guard row < rows, column < columns else {
return nil
}
return (row, column)
}
let origin = (x: 50.0, y: 10.0)
assert(cell(at: (x: 50, y: 10), origin: origin, side: 20, rows: 3, columns: 4)! == (0, 0))
assert(cell(at: (x: 129.9, y: 69.9), origin: origin, side: 20, rows: 3, columns: 4)! == (2, 3))
assert(cell(at: (x: 130, y: 20), origin: origin, side: 20, rows: 3, columns: 4) == nil) // right edge
assert(cell(at: (x: 49, y: 20), origin: origin, side: 20, rows: 3, columns: 4) == nil)The guard on negative values matters: Int(-0.5) is 0, so without it a
point just left of the grid would count as column 0.
Q3: A tally
Write a view TallyView with a count that starts at 0, a Stepper that
chooses how much each tap adds (1 to 10), buttons to add and to reset, and
text that shows the count in red when it is over 100.
Show solution
import SwiftUI
struct TallyView: View {
@State private var count = 0
@State private var amount = 1
var body: some View {
VStack(spacing: 12) {
Text("\(count)")
.font(.largeTitle)
.foregroundStyle(count > 100 ? .red : .primary)
Stepper("Add \(amount) each time", value: $amount, in: 1...10)
HStack {
Button("Add") { count += amount }
.buttonStyle(.glassProminent)
Button("Reset") { count = 0 }
.buttonStyle(.glass)
.disabled(count == 0)
}
}
.padding()
.frame(width: 280)
}
}The color is computed from count every time body runs, so it changes as
soon as the count passes 100, with no code watching for that moment.
Q4: A checkerboard
Write a view that draws an n by n checkerboard on a Canvas, with a
Slider choosing n from 2 to 16.
Show solution
import SwiftUI
struct CheckerboardView: View {
@State private var size = 8.0
var body: some View {
VStack {
Canvas { context, area in
let n = Int(size)
let side = min(area.width, area.height) / CGFloat(n)
for row in 0..<n {
for column in 0..<n where (row + column) % 2 == 0 {
let square = CGRect(x: CGFloat(column) * side, y: CGFloat(row) * side,
width: side, height: side)
context.fill(Path(square), with: .color(.primary))
}
}
}
.aspectRatio(1, contentMode: .fit)
Slider(value: $size, in: 2...16, step: 1) {
Text("\(Int(size)) × \(Int(size))")
}
}
.padding()
.frame(width: 320, height: 380)
}
}A square is dark when its row and column add up to an even number, which alternates both along a row and down a column.
Q5: Paint by dragging
Change LifeView so that dragging across the grid brings cells to life
(rather than toggling them, which would flicker as the drag passes over a
cell several times). Use a DragGesture(minimumDistance: 0), whose
onChanged reports the current location.
Show solution
Add a revive method to the model, which sets a cell alive and leaves live
cells alone, and use it from the gesture:
import SwiftUI
struct Life {
private(set) var cells: [[Bool]]
var rows: Int { cells.count }
var columns: Int { cells.first?.count ?? 0 }
init(rows: Int, columns: Int) {
cells = Array(repeating: Array(repeating: false, count: columns), count: rows)
}
mutating func revive(row: Int, column: Int) {
cells[row][column] = true
}
}
struct PaintView: View {
@State private var life = Life(rows: 20, columns: 20)
var body: some View {
GeometryReader { geometry in
let side = min(geometry.size.width / CGFloat(life.columns),
geometry.size.height / CGFloat(life.rows))
Canvas { context, _ in
for row in 0..<life.rows {
for column in 0..<life.columns where life.cells[row][column] {
context.fill(Path(CGRect(x: CGFloat(column) * side, y: CGFloat(row) * side,
width: side, height: side)),
with: .color(.green))
}
}
}
.gesture(DragGesture(minimumDistance: 0).onChanged { drag in
let row = Int(drag.location.y / side)
let column = Int(drag.location.x / side)
if drag.location.x >= 0, drag.location.y >= 0,
row < life.rows, column < life.columns {
life.revive(row: row, column: column)
}
})
}
.aspectRatio(1, contentMode: .fit)
.frame(width: 400)
}
}minimumDistance: 0 makes a plain click count as a drag too, so one gesture
handles both. Setting a cell alive is idempotent, doing it twice is the
same as doing it once, which is exactly the property that toggling lacks.
Q6 (optional): Bouncing balls
Write a model Balls for a box of balls that move in straight lines and
bounce off the walls, with a step(seconds:) method, then a view that draws
them and advances the model 60 times a second. Test the model: a ball moving
right at 10 units per second in a box 100 wide, starting at x = 95, should
be at x = 95 moving left after one second.
Show solution
struct Ball {
var x: Double
var y: Double
var dx: Double
var dy: Double
}
struct Balls {
let width: Double
let height: Double
var balls: [Ball]
mutating func step(seconds: Double) {
for i in balls.indices {
balls[i].x += balls[i].dx * seconds
balls[i].y += balls[i].dy * seconds
if balls[i].x < 0 || balls[i].x > width {
balls[i].dx = -balls[i].dx
balls[i].x = balls[i].x < 0 ? -balls[i].x : 2 * width - balls[i].x
}
if balls[i].y < 0 || balls[i].y > height {
balls[i].dy = -balls[i].dy
balls[i].y = balls[i].y < 0 ? -balls[i].y : 2 * height - balls[i].y
}
}
}
}
var box = Balls(width: 100, height: 100, balls: [Ball(x: 95, y: 50, dx: 10, dy: 0)])
box.step(seconds: 1)
assert(box.balls[0].x == 95 && box.balls[0].dx == -10)A ball that would end up past a wall is reflected: it travels the 5 units to
the wall and 5 back, so it lands at 95. The view draws each ball as a circle
with Path(ellipseIn:) and calls step(seconds: 1 / 60) in a task loop
that sleeps for a sixtieth of a second, just like LifeView.
What’s next
Next lesson: testing data structures properly, in a package with a real test suite, before we start building them.