skip to content

In SwiftUI, how do you build a horizontally paged stories carousel, and when do you pick scrollTargetBehavior(.paging) over .viewAligned?

level: seniorimportance: should knowfreq 48%

answer

  1. iOS 17 scroll targets
  2. container pages versus view edges
  3. mark the layout that holds targets
  4. peeking neighbours need view alignment

basics

~10 s

Put the stories in a LazyHStack inside ScrollView(.horizontal) and add scrollTargetBehavior (iOS 17). Use .paging when each story fills the scroll view; use .viewAligned with scrollTargetLayout() when cards are narrower and neighbours peek.

solid answer

~40 s

Since iOS 17, `scrollTargetBehavior(_:)` decides where a scroll gesture comes to rest. `.paging` settles on container-aligned boundaries, page by page, so it fits when every item is exactly one container wide, such as full-screen stories sized with `containerRelativeFrame(.horizontal)`. `.viewAligned` settles on the edges of individual views, and only the views in the container marked with `scrollTargetLayout()` count; forget that modifier and there are no card views to settle on. View alignment suits cards that are narrower than the screen, with `safeAreaPadding` or `contentMargins` letting neighbours peek. `.viewAligned(limitBehavior:)` controls how far one swipe goes, and iOS 18 adds `.alwaysByOne`. Track the current story with `scrollPosition(id:)`, and add depth with `scrollTransition`, which applies visual effects by scroll phase.

code

swift · 35 lines
swift
import SwiftUI

struct Story: Identifiable {
    let id: Int
    let title: String
}

struct StoriesCarousel: View {
    let stories: [Story]
    @State private var currentID: Story.ID?

    var body: some View {
        ScrollView(.horizontal) {
            LazyHStack(spacing: 12) {
                ForEach(stories) { story in
                    Text(story.title)
                        .frame(maxHeight: .infinity)
                        .containerRelativeFrame(.horizontal)
                        .background(.tint.opacity(0.2), in: .rect(cornerRadius: 16))
                        .scrollTransition { content, phase in
                            content
                                .scaleEffect(phase.isIdentity ? 1 : 0.92)
                                .opacity(phase.isIdentity ? 1 : 0.6)
                        }
                }
            }
            .scrollTargetLayout()
        }
        .scrollTargetBehavior(.viewAligned(limitBehavior: .alwaysByOne))
        .safeAreaPadding(.horizontal, 24)
        .scrollPosition(id: $currentID)
        .scrollIndicators(.hidden)
        .frame(height: 220)
    }
}

go deeper

for a junior

Recall that iOS 17 added scrollTargetBehavior with two presets, .paging and .viewAligned, for snapping a ScrollView.

for a middle

Explain container-sized pages versus view edges, why scrollTargetLayout is required for view alignment, and how containerRelativeFrame sizes each page.

for a senior

Diagnose misaligned pages, cards that never snap and multi-card flings on iPad, and choose limitBehavior and padding to fix them.

for a principal

Decide whether the carousel can require iOS 17 or must keep a fallback, and set one carousel component the team reuses.

## Scroll targets in SwiftUI By default a `ScrollView` stops wherever its deceleration ends. **`scrollTargetBehavior(_:)`**, added in iOS 17, lets you change where a scroll gesture comes to rest. A behaviour is any type conforming to **`ScrollTargetBehavior`**, which adjusts a proposed `ScrollTarget` in `updateTarget(_:context:)`. SwiftUI ships two: - **`.paging`** (`PagingScrollTargetBehavior`): "aligns scroll targets to container-based geometry". The scroll view uses its own geometry and settles on container-aligned boundaries, page by page. - **`.viewAligned`** (`ViewAlignedScrollTargetBehavior`): "aligns scroll targets to view-based geometry". The scroll view always settles on the edge of one of its child views. ## Choosing between them | | `.paging` | `.viewAligned` | |---|---|---| | **Settles on** | Container-aligned boundaries | Edges of individual views | | **Item size** | Each item should be one container wide | Any width, including cards that let neighbours peek | | **Needs `scrollTargetLayout()`** | No | Yes, on the stack holding the items | | **Limit control** | None to configure | `limitBehavior`: `.automatic`, `.always`, and from iOS 18 `.alwaysByFew`, `.alwaysByOne` | | **Fits** | Full-screen stories, vertical video feeds | Story cards, cover carousels | The classic bug with `.paging` is pairing it with cards narrower than the screen: pages are container-sized, so after a few swipes the cards sit across page boundaries. The classic bug with `.viewAligned` is forgetting **`scrollTargetLayout()`**. That modifier, applied to the `LazyHStack` or `HStack` holding the cards, tells SwiftUI that each child of that layout is a target to align to. ## Building the stories carousel 1. `ScrollView(.horizontal)` containing a `LazyHStack`, so stories are created as they approach the screen. 2. Size each story with **`containerRelativeFrame(.horizontal)`**, which sizes it relative to the nearest container, here the scroll view, minus its safe-area insets. 3. Add `.scrollTargetLayout()` to the `LazyHStack`. 4. Add `.scrollTargetBehavior(.viewAligned(limitBehavior: .alwaysByOne))` on iOS 18, or `.viewAligned` on iOS 17. 5. Add `.safeAreaPadding(.horizontal, 24)` so each story is narrower than the screen and its neighbours peek in. Apple's view-aligned example uses the same pairing. 6. Bind **`scrollPosition(id:)`**, iOS 17, to know which story is current, for example to drive a progress bar, or write to it to move programmatically. 7. Hide indicators with `scrollIndicators(.hidden)`. ## Knowing which story is current `scrollPosition(id:anchor:)` binds an optional id. With the stories' `LazyHStack` marked by `scrollTargetLayout()`, SwiftUI writes the id of the leading-most visible story into the binding as the reader swipes, and writing an id scrolls to that story. That single binding can drive a progress indicator, an analytics event when the story changes, or an "advance after five seconds" timer that sets the next id. On iOS 18, `onScrollTargetVisibilityChange(idType:threshold:_:)` reports the ids of every target currently past a visibility threshold, which helps when two cards are partly visible at once. Note that Apple's own example on that page writes the label as `for:`, while the SDK declares `idType:`; code must use `idType:`. ## Scroll-driven effects **`scrollTransition(_:axis:transition:)`**, iOS 17, applies visual effects as a view moves through the visible region. Its closure receives a **`ScrollTransitionPhase`**: `topLeading` or `bottomTrailing` while the view approaches from an edge, and `identity` once it is visible. Scale and fade cards that are not in the identity phase. Apple's guidance is that the identity phase should generally make no visual change, because it applies for as long as the view is visible. The closure returns visual effects only; it is not a place for side effects such as starting playback. ## Limits and alternatives - `ViewAlignedScrollTargetBehavior` documents its default: it limits the number of views a horizontal scroll moves in a compact horizontal size class (and a vertical one in a compact vertical size class), and otherwise imposes no limit unless you set one. - For behaviour neither preset provides, such as snapping to every 10 points, conform your own type to `ScrollTargetBehavior`. - A paged `TabView` style is the older paging route and is covered with tabs; the scroll-target APIs keep a real `ScrollView` and lazy stack. - An app that still supports iOS 16 has none of these modifiers there; gate them with availability checks or keep the older approach for those devices.

  • How would you make a vertical, full-screen video feed snap one video at a time?
    Use a vertical ScrollView with a LazyVStack(spacing: 0), size each video with containerRelativeFrame([.horizontal, .vertical]) so it is exactly one container tall, and apply scrollTargetBehavior(.paging). Because each item equals the page size, container-based paging lands on video boundaries.
  • Why might a view-aligned carousel move several cards on iPad but one on iPhone?
    ViewAlignedScrollTargetBehavior's default limit applies only in a compact size class along the scroll axis; in regular width it imposes no limit, so a fling can travel several cards. Pass a limitBehavior such as .always, or .alwaysByOne from iOS 18, to constrain it everywhere.
  • Can scrollTransition start playing a story's video when it becomes current?
    No. Its closure maps a phase to visual effects such as scale or opacity and returns them; it is not an action hook. Drive playback from state instead, for example the id bound with scrollPosition(id:) or onScrollVisibilityChange on iOS 18.

  • .paging snaps to each card's edge, whatever the card width.
  • .viewAligned works without marking any layout as the scroll target layout.
  • Paging in a ScrollView requires a page-style TabView underneath.
  • scrollTransition is where you start playback when a card becomes visible.
  • The paging behaviours are available back to iOS 15.

scrollTargetBehavior, scrollTargetLayout, scrollPosition(id:), containerRelativeFrame and scrollTransition need iOS 17; the alwaysByOne and alwaysByFew limit behaviours need iOS 18.