How it works
A ScrollView is a container view that lets its content extend beyond the bounds of the available space and makes that overflow reachable by scrolling. Use it whenever the views you want to present may be taller or wider than the screen — long lists of text, stacks of cards, or any layout whose size you can't guarantee will fit. Unlike List, a ScrollView imposes no row styling or structure of its own: it simply measures its single content view, and if that content overflows along the scroll axis, it becomes draggable. Reach for it when you need scrolling but want full control over how the content is laid out and styled.
Wrap content in a ScrollView
ScrollViewtakes a single content view, supplied as a trailing closure, and provides vertical scrolling by default. Here the closure holds aVStack, so the whole stack scrolls as one unit; theScrollViewmeasures that stack and enables dragging only when it exceeds the visible height.Give it content taller than the viewport
Scrolling only engages when the content overflows. The
ForEach(1...20, id: \.self)builds twentyText("Row \(i)")rows inside theVStack, producing far more height than fits on screen — which is exactly the condition that makes theScrollViewscroll rather than clip.Choose the scroll axis
The initializer accepts an axis set as its first parameter; omitting it, as here, defaults to
.vertical. Pass.horizontalfor sideways scrolling or[.horizontal, .vertical]for both. The axis you pick determines which dimension of the content view theScrollViewlets overflow and drag.Lay out and pad content independently
Because
ScrollViewadds no styling of its own, the appearance of each item comes entirely from the content. The per-row.padding(),.background(Color.blue.opacity(0.1)), and.cornerRadius(8), plus the outer.padding()on theVStack, all live inside the scrolled content and travel with it as you scroll.
ForEach(1...20, id: \.self) to ForEach(1...3, id: \.self) — with only three rows the content fits on screen and the ScrollView stops scrolling, showing that it engages only when its content overflows.Example & preview
Press Run live & edit to compile it in your browser — then edit the Swift on the left and the preview re-renders live.
struct ScrollViewDemo: View {
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
ForEach(1...20, id: \.self) { i in
Text("Row \(i)")
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
.background(Color.blue.opacity(0.1))
.cornerRadius(8)
}
}
.padding()
}
}
}