Mobile development · Beginner · 24 min
Lay out SwiftUI screens with stacks, lists and NavigationStack
By Padding · Updated 18 Nov 2026
Swift 6.4 · Xcode 27.1 · macOS Tahoe 26.6
You will build a two-screen clinic directory in SwiftUI with stacked rows, a sectioned list with swipe actions, typed navigation, a toolbar button that opens a sheet, and previews that prove the layout holds at large text sizes and in dark mode.
On this page
A real app screen is rarely one view. It is rows made of smaller pieces, lists grouped into sections, a way to move to a detail screen and back, and a button that opens a form. SwiftUI builds all of that from a small set of building blocks: stacks arrange views, List scrolls and groups rows, and NavigationStack moves between screens.
In this tutorial you build a clinic directory for a fictional health network in Lagos. The first screen lists clinics by area. Swiping a row marks it as a favourite or hides it. Tapping a row opens a detail screen, and a plus button opens a sheet where you add a clinic and land straight on its new page. Last, you check the screens at the largest text sizes and in dark mode, because a layout that only works at the default size is not finished.
You need Xcode 27.1, which includes Swift 6.4 and the iOS 27.1 SDK and runs on macOS Tahoe 26.6 or later. If you have not used SwiftUI before, start with build your first iOS app with SwiftUI, which covers the project template, @State and the canvas.
Step 1 · Create the project and the clinic model
In Xcode, choose File, New, Project, then the iOS App template. Name it ClinicDirectory, choose SwiftUI for the interface and Swift for the language, and leave Storage as None.
Add a new Swift file with File, New, File from Template, choose Swift File, and name it Clinic.swift. Replace its contents with this:
import Foundation
struct Clinic: Identifiable, Hashable, Sendable {
let id = UUID()
var name: String
var area: String
var hours: String
var services: String
var isFavourite = false
var initials: String {
name.split(separator: " ")
.prefix(2)
.compactMap { $0.first }
.map { String($0) }
.joined()
}
}
extension Clinic {
static let samples: [Clinic] = [
Clinic(name: "Yaba Community Health Centre", area: "Yaba",
hours: "Mon to Sat, 8:00 to 18:00",
services: "Antenatal care, vaccinations, malaria testing"),
Clinic(name: "Sabo Children's Clinic", area: "Yaba",
hours: "Every day, 7:00 to 21:00",
services: "Child health, nutrition checks, vaccinations"),
Clinic(name: "Surulere Family Clinic", area: "Surulere",
hours: "Mon to Fri, 9:00 to 17:00",
services: "General practice, blood pressure checks"),
Clinic(name: "Ilé Ìwòsàn Ìyá àti Ọmọ", area: "Ikeja",
hours: "Mon to Sat, 8:00 to 16:00",
services: "Maternity care, family planning, postnatal visits"),
Clinic(name: "Ikeja Mother and Child Clinic and Maternity Annexe", area: "Ikeja",
hours: "Open 24 hours",
services: "Deliveries, emergency obstetric care"),
]
}What each part is for:
Identifiablegives each clinic a stableid, so a list can tell rows apart when they move or disappear.Hashablelets a clinic be a navigation value. You use that in the navigation step.Sendablesays the value is safe to share across concurrency domains, which Swift 6 checks for static data such assamples.- The sample data is deliberately awkward. One name uses Yoruba tone marks and one is long enough to wrap. If your users read in Yoruba, Hausa, Amharic or any language with diacritics, put real names like these in your sample data from day one, so layout problems show up in previews instead of in the field.
Check it worked
Build with Command+B. The build succeeds with no errors, and Clinic.swift appears in the project navigator next to ContentView.swift.
Step 2 · Build one row with HStack, VStack and ZStack
Each list row has three parts side by side: a round badge with the clinic's initials, the name with the opening hours below it, and a star if it is a favourite. That is one horizontal stack holding a layered stack, a vertical stack and an image.
Create a Swift file called ClinicRow.swift:
import SwiftUI
struct ClinicRow: View {
let clinic: Clinic
@ScaledMetric(relativeTo: .headline) private var badgeSize: CGFloat = 44
var body: some View {
HStack(alignment: .top, spacing: 12) {
ZStack {
Circle()
.fill(.indigo.opacity(0.15))
Text(clinic.initials)
.font(.headline)
.foregroundStyle(.indigo)
}
.frame(width: badgeSize, height: badgeSize)
.accessibilityHidden(true)
VStack(alignment: .leading, spacing: 4) {
Text(clinic.name)
.font(.headline)
Text(clinic.hours)
.font(.subheadline)
.foregroundStyle(.secondary)
}
Spacer(minLength: 0)
if clinic.isFavourite {
Image(systemName: "star.fill")
.foregroundStyle(.primary)
.accessibilityLabel("Favourite")
}
}
.padding(.vertical, 4)
}
}
#Preview {
List {
ClinicRow(clinic: Clinic.samples[0])
ClinicRow(clinic: Clinic.samples[4])
}
}The choices that matter:
ZStacklayers its children from back to front, so the text sits on top of the circle. The frame on theZStacksets the size of both.HStack(alignment: .top, spacing: 12)puts 12 points between children and lines up their top edges. With the default centre alignment, the badge would float halfway down a three-line name.VStack(alignment: .leading, spacing: 4)stacks the name above the hours and lines both up on the left. Without.leading, a short line is centred under a long one.Spacer(minLength: 0)pushes the star to the trailing edge, and the zero minimum means it gives up all its space before the name has to wrap.@ScaledMetricgrows the 44-point badge in step with the headline font when the reader picks a bigger text size. A fixed number would leave a tiny badge next to huge text.- No
lineLimit. The name wraps to as many lines as it needs. Truncating clinic names with "..." hides the one word that tells two clinics apart.
.accessibilityHidden(true) stops VoiceOver from reading the initials, which only repeat the name. The star gets a spoken label instead.
Check it worked
Open the canvas with Option+Command+Return. The preview shows two rows. The long Ikeja name wraps onto two or three lines, its "IM" badge stays level with the first line, and nothing ends in "...".
Step 3 · Group the clinics into a list with sections
Create ClinicDirectoryView.swift. This first version shows every clinic, grouped by area, in alphabetical order:
import SwiftUI
struct ClinicDirectoryView: View {
@State private var clinics = Clinic.samples
private var areas: [String] {
Set(clinics.map(\.area)).sorted()
}
var body: some View {
NavigationStack {
List {
ForEach(areas, id: \.self) { area in
Section(area) {
ForEach(rows(in: area)) { clinic in
ClinicRow(clinic: clinic)
}
}
}
}
.navigationTitle("Clinics")
}
}
private func rows(in area: String) -> [Clinic] {
clinics.filter { $0.area == area }
}
}
#Preview {
ClinicDirectoryView()
}areas turns the area names into a set to remove repeats, then sorts them. The outer ForEach makes one Section per area, with the area name as its header, and the inner ForEach fills each section with that area's clinics. List handles the scrolling, the row separators and the grouped style, so you do not build any of that yourself.
The NavigationStack is here already so the title shows. The next steps give it more to do.
Now point the app at the new screen. Open ClinicDirectoryApp.swift and change ContentView() inside WindowGroup to ClinicDirectoryView(). Then delete ContentView.swift (choose Move to Trash), since nothing uses it any more.
Check it worked
The canvas for ClinicDirectoryView.swift shows a large "Clinics" title and three sections in order: Ikeja with two clinics, Surulere with one and Yaba with two. Press Command+R to run it in the Simulator and you see the same list.
Step 4 · Add swipe actions to the rows
Swipe actions are buttons that appear when the reader drags a row sideways. Add two: swipe right to mark a favourite, swipe left to hide a clinic from the list.
In ClinicDirectoryView.swift, replace the inner ForEach with this version:
ForEach(rows(in: area)) { clinic in
ClinicRow(clinic: clinic)
.swipeActions(edge: .leading) {
Button {
toggleFavourite(clinic)
} label: {
Label(clinic.isFavourite ? "Unfavourite" : "Favourite",
systemImage: clinic.isFavourite ? "star.slash" : "star")
}
.tint(.orange)
}
.swipeActions(edge: .trailing) {
Button(role: .destructive) {
hide(clinic)
} label: {
Label("Hide", systemImage: "eye.slash")
}
}
}Then add these two functions below rows(in:):
private func toggleFavourite(_ clinic: Clinic) {
if let index = clinics.firstIndex(where: { $0.id == clinic.id }) {
clinics[index].isFavourite.toggle()
}
}
private func hide(_ clinic: Clinic) {
clinics.removeAll { $0.id == clinic.id }
}edge: .leading puts the favourite button under a swipe to the right (in a left-to-right language) and .trailing puts Hide under a swipe to the left. The .destructive role colours Hide red and marks it as a destructive action. Full swipe is a separate setting: swipeActions(edge:allowsFullSwipe:content:) has allowsFullSwipe set to true by default, so a long swipe on either edge runs the first action on that edge straight away, Favourite as well as Hide. Pass allowsFullSwipe: false if you want people to tap the button instead. Both functions find the clinic by its id and change clinics, which is @State, so SwiftUI redraws the list. When the last clinic in an area is hidden, that area drops out of areas and its section disappears with it.
Swipe actions are hidden until someone swipes, and people using VoiceOver or Switch Control reach them only through an Actions menu. In a production app, offer the same actions somewhere visible too, such as on the detail screen.
Check it worked
In the canvas, turn on the interactive preview or run the app. Swipe the Surulere row to the right and tap Favourite: a star appears at the end of the row. Swipe it to the left and tap Hide: the row goes and the Surulere section goes with it.
Step 5 · Navigate to a detail screen with a typed path
NavigationStack can keep track of where the reader is as an array of values. Each value in the array is one screen pushed on top of the list. You choose the type, here Clinic, and tell the stack which view to show for it.
First create the detail screen. Make a file called ClinicDetailView.swift:
import SwiftUI
struct ClinicDetailView: View {
let clinic: Clinic
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 20) {
VStack(alignment: .leading, spacing: 4) {
Text(clinic.area)
.font(.subheadline.weight(.semibold))
Text(clinic.name)
.font(.title2.bold())
}
.foregroundStyle(.white)
.padding()
.frame(maxWidth: .infinity, minHeight: 140, alignment: .bottomLeading)
.background(.indigo.gradient, in: RoundedRectangle(cornerRadius: 16))
infoRow("Hours", systemImage: "clock", value: clinic.hours)
infoRow("Services", systemImage: "cross.case", value: clinic.services)
}
.padding()
}
.navigationTitle(clinic.name)
.navigationBarTitleDisplayMode(.inline)
}
private func infoRow(_ title: String, systemImage: String, value: String) -> some View {
HStack(alignment: .firstTextBaseline, spacing: 12) {
Label(title, systemImage: systemImage)
.font(.headline)
Text(value)
}
}
}
#Preview {
NavigationStack {
ClinicDetailView(clinic: Clinic.samples[3])
}
}The header is a VStack with a coloured background. minHeight: 140 gives it a banner shape at normal sizes, while letting it grow when the text grows, and alignment: .bottomLeading pins the text to the lower left corner. .background(_:in:) draws the shape behind the content and takes the content's size, which is what you want here. A ZStack sizes itself to its largest child, which suits the fixed-size badge in the row but not a banner that must follow its text. ScrollView makes the screen scroll when the text is too tall to fit. The info row's .firstTextBaseline alignment lines up the label and the value on the baseline of their first lines.
Now wire it into the list. Back in ClinicDirectoryView.swift, make three changes:
- Add the path below
clinics:
@State private var path: [Clinic] = []- Change
NavigationStack {toNavigationStack(path: $path) {. - Wrap the row in a
NavigationLinkthat carries the clinic as its value, keeping the two.swipeActionsmodifiers on the link, and addnavigationDestinationafter.navigationTitle("Clinics"):
ForEach(rows(in: area)) { clinic in
NavigationLink(value: clinic) {
ClinicRow(clinic: clinic)
}
.swipeActions(edge: .leading) {
// the favourite button from the previous step
}
.swipeActions(edge: .trailing) {
// the Hide button from the previous step
}
}.navigationTitle("Clinics")
.navigationDestination(for: Clinic.self) { clinic in
ClinicDetailView(clinic: clinic)
}Keep the real button code where the comments are. When the reader taps a row, the NavigationLink appends its clinic to path, and navigationDestination(for: Clinic.self) builds the screen for it. Back removes it again. Put navigationDestination on the List, as here, rather than inside the ForEach: a lazily built list may not have built the row that holds it, and the stack then cannot find the destination.
Because path is plain data you own, your code can navigate too. path.append(someClinic) opens a clinic, path.removeLast() goes back one screen and path.removeAll() returns to the list. The next step uses append.
Check it worked
Run the app or use the interactive preview. Each row now has a chevron at its trailing edge. Tap "Ilé Ìwòsàn Ìyá àti Ọmọ": the detail screen slides in with an indigo banner reading "Ikeja" above the clinic name, the tone marks drawn correctly, and the Hours and Services rows below. The back button at the top left returns you to the list, and swipe actions still work there.
Step 6 · Add a toolbar button that opens a sheet
A sheet is a screen that slides up over the current one for a short task, here adding a clinic. Create AddClinicView.swift:
import SwiftUI
struct AddClinicView: View {
var onSave: (Clinic) -> Void
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var area = "Yaba"
@State private var hours = ""
private let areas = ["Ikeja", "Surulere", "Yaba"]
private var trimmedName: String {
name.trimmingCharacters(in: .whitespaces)
}
var body: some View {
NavigationStack {
Form {
TextField("Clinic name", text: $name)
Picker("Area", selection: $area) {
ForEach(areas, id: \.self) { Text($0) }
}
TextField("Opening hours", text: $hours)
}
.navigationTitle("New clinic")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Save") {
onSave(Clinic(name: trimmedName, area: area,
hours: hours.isEmpty ? "Hours not set" : hours,
services: "Not listed yet"))
dismiss()
}
.disabled(trimmedName.isEmpty)
}
}
}
.presentationDetents([.medium, .large])
}
}The sheet has its own NavigationStack, only so it can show a title and toolbar buttons. The .cancellationAction and .confirmationAction placements put Cancel and Save where iOS readers expect them, without you choosing a side. dismiss comes from the environment and closes the sheet. presentationDetents([.medium, .large]) opens the sheet at half height, with a grabber to pull it to full height. The view does not know about the list: it hands the new clinic to whoever presented it through onSave.
Now present it from the directory. In ClinicDirectoryView.swift, add one more state property:
@State private var showingAddClinic = falseand add these two modifiers after .navigationDestination, still inside the NavigationStack:
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button("Add clinic", systemImage: "plus") {
showingAddClinic = true
}
}
}
.sheet(isPresented: $showingAddClinic) {
AddClinicView { newClinic in
clinics.append(newClinic)
path.append(newClinic)
}
}The plus button sets showingAddClinic to true and the sheet appears. On Save, the new clinic goes into the list and onto the path, so when the sheet closes the reader is already on the new clinic's detail screen. The button's title, "Add clinic", is not drawn next to the icon in the navigation bar, but VoiceOver reads it, so the icon-only button still has a name.
Check it worked
Run the app. A plus appears at the top right of the Clinics screen. Tap it: a half-height sheet titled "New clinic" slides up with Save greyed out. Type "Ojota Health Post", pick Ikeja and tap Save. The sheet closes on the detail screen for Ojota Health Post, and Back shows it in the Ikeja section. Tap plus again and Cancel: the sheet closes and nothing is added.
Step 7 · Make the layout hold at large text sizes
iOS readers can raise the text size well beyond the default in Settings, and the largest accessibility sizes are several times bigger. Many people use them, including older relatives sharing a phone and anyone reading on a small screen in bright sun. Text styles such as .headline and .subheadline already scale, and the row's @ScaledMetric badge follows. The weak spot is the detail screen's info rows: side by side, a huge "Services" label squeezes the value into a thin column.
Fix it by choosing the layout from the reader's text size. In ClinicDetailView.swift, add the environment value and a layout property below let clinic: Clinic:
@Environment(\.dynamicTypeSize) private var typeSize
private var infoLayout: AnyLayout {
typeSize.isAccessibilitySize
? AnyLayout(VStackLayout(alignment: .leading, spacing: 4))
: AnyLayout(HStackLayout(alignment: .firstTextBaseline, spacing: 12))
}Then replace the HStack(alignment: .firstTextBaseline, spacing: 12) line in infoRow with infoLayout, so the function reads:
private func infoRow(_ title: String, systemImage: String, value: String) -> some View {
infoLayout {
Label(title, systemImage: systemImage)
.font(.headline)
Text(value)
}
}isAccessibilitySize is true for the five largest sizes. AnyLayout wraps either layout in one type, so SwiftUI can switch between them and animate the change without rebuilding the label and the text. You could shrink the font instead, but readers chose that size on purpose. Changing the arrangement keeps their choice.
Check it worked
Open ClinicDetailView.swift in the canvas. In current versions of Xcode, the canvas has a Variants control at the bottom that shows the preview at every Dynamic Type size side by side (the control's name and place can change between versions). At the accessibility sizes, each label sits above its value, every word of the clinic name is visible in the banner, and nothing ends in "...". In the Simulator, you can change the size while the app runs from the Environment Overrides button in Xcode's debug bar.
Step 8 · Pin the hard cases in named previews
Variants are good for a quick look. Named previews stay in the file, so every time you open it you see the cases that tend to break. Replace the #Preview block at the bottom of ClinicDirectoryView.swift with these four:
#Preview("Default") {
ClinicDirectoryView()
}
#Preview("Largest text") {
ClinicDirectoryView()
.dynamicTypeSize(.accessibility5)
}
#Preview("Dark mode") {
ClinicDirectoryView()
.preferredColorScheme(.dark)
}
#Preview("Detail, large text, dark") {
NavigationStack {
ClinicDetailView(clinic: Clinic.samples[4])
}
.dynamicTypeSize(.accessibility3)
.preferredColorScheme(.dark)
}.dynamicTypeSize(_:) forces a text size for everything inside, and .preferredColorScheme(.dark) forces dark mode. You did not set any colours that only work on white: .secondary, .primary and the system list background adapt by themselves, and the indigo banner keeps its white text readable in both modes. Opening a file builds its previews, so on a slower Mac keep this file to a handful.
Check it worked
The canvas shows four tabs, named after the previews. In "Largest text", the list rows are tall, the initials badges are larger than in "Default", and every clinic name is complete. In "Dark mode", the background is black, the text is light and the hours are a softer grey. In "Detail, large text, dark", the long Ikeja name wraps inside the banner and each label sits above its value. If any preview shows a cut-off word, look for a fixed frame(height:) or a lineLimit near it.
Next steps
- Make the same screens feel right on both platforms: follow iOS and Android conventions in one design.
- Go back over the Swift language itself: hello world in Swift.
- Revisit the basics of the canvas, the Simulator and running on a phone: build your first iOS app with SwiftUI.
Related tutorials
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
- Store data in a SwiftUI app with SwiftDataYou will build a small shop stock app that saves suppliers and products on the iPhone with SwiftData, lists them with sorted and filtered queries, survives a schema change through a migration plan, and is checked by tests that run against an in-memory store.
- Store data in a Flutter app with Drift and SQLiteYou will build a small shop credit book in Flutter 3.50 that keeps customers and what they owe in SQLite through Drift 2.35, with typed queries, a join, a list that redraws itself from a watch() stream, a tested schema migration and in-memory tests for all of it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials