[SwiftUI] Observing scroll offset of a List

November 04, 2024 ā€¢ 2 min read ā€¢ #swift, #ios, #indie, #minimalist phone

Iā€™m doing some design explorations for my Minimalist Phone app.

Iā€™m trying to observe the scroll offset of a SwiftUI List. This is useful to create something like parallax stretching headers or content manipulation based on scrolling. My idea for the Minimalist Phone app is to keep the home screen as minimal as possible, and only reveal additional UI controls with scrolling geatures.

I asked the same question few years ago on StackOverflow. At that point, SwiftUI was not mature enough, and we needed a lot of hacks to make it working.

With modern SwiftUI, it is very easy now to observe the scroll offset of the List.

import SwiftUI

struct ContentView: View {
    @State private var scrollOffset: CGFloat = 0

    var body: some View {
        ScrollView {
            VStack {
                ForEach(0..<50) { index in
                    Text("Item \(index)")
                        .frame(maxWidth: .infinity)
                        .padding()
                        .background(Color.gray.opacity(0.2))
                        .cornerRadius(8)
                        .padding(.horizontal)
                }
            }
            .background(GeometryReader { geometry in
                Color.clear
                    .onAppear {
                        scrollOffset = geometry.frame(in: .global).minY
                    }
                    .onChange(of: geometry.frame(in: .global).minY) { oldValue, newValue in
                        scrollOffset = newValue
                    }
            })
        }
        .overlay(
            Text("Scroll Offset: \(scrollOffset, specifier: "%.0f")")
                .padding()
                .background(Color.black.opacity(0.7))
                .foregroundColor(.white)
                .cornerRadius(10)
                .padding(),
            alignment: .top
        )
    }
}

#Preview {
    ContentView()
}

The result can be seen in the following video

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


Ā© An Tran - 2024