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
Observing the scroll offset of a SwiftUI List is much easier nowadays š pic.twitter.com/LTskT1ZUY6
— An Tran (@antranapp) November 3, 2024