skip to content

How does SwiftUI's visualEffect modifier let a parallax header react to its own position without changing the layout?

level: middleimportance: should knowfreq 35%

answer

  1. drawing, not layout
  2. a placeholder plus a proxy
  3. offset, scale, blur, opacity
  4. a Sendable closure

basics

~20 s

visualEffect(_:) (iOS 17) gives a closure the view's GeometryProxy and lets it return rendering effects such as offset, scale or blur. Effects never change layout, so a header can move with its own position without loops or state writes.

solid answer

~40 s

`visualEffect(_:)`, added in iOS 17, takes a closure that receives a placeholder for the view and a `GeometryProxy`. You return effects built on the placeholder, such as `offset`, `scaleEffect`, `blur` or `opacity`. Apple's documentation says visual effects change a view's appearance without changing its ancestors or descendants, and because they don't affect layout they are safe where layout changes are not allowed. For a parallax header you read `proxy.frame(in: .named("article"))`, the header's position in the scroll content's named space, and offset the image by a fraction of `minY`. Nothing writes `@State`, so scrolling never turns into state changes; SwiftUI recomputes the effect from the new geometry. The closure is `@Sendable`, so it can't read main-actor view state directly; copy what it needs into constants first.

code

swift · 24 lines
swift
struct ArticleScreen: View {
    var body: some View {
        ScrollView {
            VStack(spacing: 0) {
                Image("harbor")
                    .resizable()
                    .scaledToFill()
                    .frame(height: 260)
                    .clipped()
                    .visualEffect { content, proxy in
                        let minY = proxy.frame(in: .named("article")).minY
                        // Scrolling up makes minY negative; move down by half of it.
                        return content.offset(y: minY < 0 ? -minY / 2 : 0)
                    }
                Text("Harbour lights")
                    .font(.largeTitle.bold())
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .padding()
                    .background(.background)
            }
        }
        .coordinateSpace(.named("article"))
    }
}

go deeper

for a junior

Recall that visualEffect gives you the view's geometry and lets you return effects such as offset, scale and blur, and that it arrived in iOS 17.

for a middle

Explain why the closure can read position safely: effects change drawing, not layout, so the geometry it reads isn't changed by its own output. Show the named coordinate space on the scroll view.

for a senior

Compare it with a GeometryReader wrapper and with measuring into @State, name the costs of each, and handle the details: clipping order, a background on the text below, and the Sendable closure in Swift 6 mode.

for a principal

The decision is small: standardise on visualEffect for position-driven decoration so per-frame state writes don't creep into scrolling screens, and leave scroll-phase effects to scrollTransition.

## The problem a parallax header poses A **parallax header** is an image at the top of a scrolling article that moves more slowly than the text as the reader scrolls. To do that, the image needs to know **where it currently is**, and then draw itself somewhere slightly different. The naive SwiftUI approaches both hurt: - Wrapping the header in a `GeometryReader` and applying `.offset` from its frame works, but the reader is a flexible container that needs a fixed frame to avoid swallowing space. - Measuring the position, writing it into `@State` and then reading that state to offset the image turns every frame of scrolling into a state change and a `body` re-run, and risks a feedback loop if the offset affects what is measured. ## What visualEffect(_:) does `visualEffect(_:)` arrived in **iOS 17**, so it is available on the usual deployment floor. Its closure receives two arguments: 1. **A placeholder for the view** (`EmptyVisualEffect`). You call effect methods on it and return the result. 2. **A `GeometryProxy`** for the view, so `size`, `frame(in:)` and the other proxy members are available. The returned value is a `VisualEffect`. You don't conform to that protocol yourself; you build effects by chaining its methods. The available effects are all **rendering effects**: - translation: `offset(x:y:)`, `offset(_:)` - scale and rotation: `scaleEffect(_:anchor:)`, `rotationEffect(_:anchor:)`, `rotation3DEffect` - colour and visibility: `opacity(_:)`, `blur(radius:opaque:)`, `brightness(_:)`, `saturation(_:)`, `grayscale(_:)` - shader effects such as `colorEffect`, which belong to the drawing material What is **not** there is anything that changes layout: no `padding`, no `frame`, no new subviews. ## Why it can read geometry safely Apple's documentation states the key rule: visual effects change the visual appearance of a view **without changing its ancestors or descendants**, and because they don't impact layout they are safe to use where layout modification is not allowed, for example as a function of position read through a geometry proxy. The loop that haunts "measure then set state" cannot form: the effect moves the pixels, not the frame, so the frame it reads is unaffected by its own output. | Approach | Writes state per frame? | Touches layout? | Extra container? | |---|---|---|---| | `GeometryReader` + `.offset` | No | Reader is flexible | Yes | | Measure into `@State`, then `.offset` | Yes | Can loop | Often | | `visualEffect(_:)` | No | No | No | ## Building the header The steps: 1. Give the scroll content's container a name with `.coordinateSpace(.named("article"))` on the `ScrollView`, so positions are measured from the scroll view's frame. 2. Size and clip the image first (`.frame(height:)`, `.clipped()`), so the effect moves a finished image. 3. In `visualEffect`, read `proxy.frame(in: .named("article")).minY`. At rest it is zero; scrolling up makes it negative. 4. Return `content.offset(y: -minY / 2)` while `minY` is negative, so the image travels at half the speed of the text. 5. Give the text below a background so the image slides **under** it rather than showing through. A pull-down stretch works the same way: when `minY` is positive the scroll view is pulled past its top, and you can pin the image with `offset(y: -minY)` and grow it with `scaleEffect(1 + minY / height, anchor: .bottom)`. Skip the clip after the effect, or the enlarged part is cut off. ## Things to watch - **The closure is `@Sendable`.** In the Swift 6 language mode it cannot read main-actor-isolated view state such as a `@State` property. Copy the values you need into local constants in `body` and capture those. - **Keep the closure cheap.** It is recomputed whenever the view's geometry changes, which while scrolling is often; do arithmetic there, not work. - **Scroll-driven alternatives exist.** `scrollTransition` and the scroll geometry callbacks, covered with scroll views, give you a phase or scroll metrics; `visualEffect` is the general tool when you want an arbitrary function of the view's own position. - **Modifier order matters.** An effect applies to the view as it is at that point in the chain: placed before `.clipped()`, the moved image is clipped to the original frame; placed after it, the clipped picture moves as a whole. The example frames and clips first. - **Respect Reduce Motion.** Read the `accessibilityReduceMotion` environment value in `body`, copy it into a local constant, and return no offset when it is on. - **Name the space.** Reading `.global` works but shifts with bars and sheets; a named space on the scroll view keeps the math stable.

  • How would you add a stretch when the user pulls the header down past the top?
    In the same closure, treat a positive `minY` as overscroll. Return `content.offset(y: -minY)` to keep the image's top pinned to the scroll view's top and `.scaleEffect(1 + minY / 260, anchor: .bottom)` to grow it upward, using the same chain in both branches. Don't clip after the effect, or the enlarged part above the frame is cut off.
  • When is scrollTransition a better fit than visualEffect?
    `scrollTransition`, covered with scroll views, hands you a phase as an item enters, sits in or leaves the visible region, which suits per-row fades and scales in a list. `visualEffect` gives you the raw proxy, so you compute any function of position in any coordinate space, which a header tracking its exact offset needs.

  • visualEffect can add padding or change a frame based on position
  • A parallax effect needs the scroll offset stored in @State
  • visualEffect changes layout, so neighbours move out of the way
  • The visualEffect closure can read any @State property it likes
  • visualEffect needs iOS 18, so iOS 17 apps can't use it