Skip to content

Instantly share code, notes, and snippets.

@5sw
Created April 25, 2023 18:41
Show Gist options
  • Save 5sw/f1d53ddcf8a194a880144b0905ac9b06 to your computer and use it in GitHub Desktop.
Save 5sw/f1d53ddcf8a194a880144b0905ac9b06 to your computer and use it in GitHub Desktop.
Pinning a view at the bottom of a scroll view
import SwiftUI
struct ContentView: View {
let itemHeight: CGFloat = 50
var body: some View {
GeometryReader { geo in
ScrollView {
VStack {
Text("Start")
Color.clear.frame(height: 800)
Text("End")
Color.blue
.frame(height: itemHeight)
.anchorPreference(key: OffsetPreference.self, value: .bottom) { anchor in
max(geo[anchor].y, geo.size.height)
}
}
}
}
.overlayPreferenceValue(OffsetPreference.self, alignment: .top) { offset in
Circle()
.frame(width: itemHeight, height: itemHeight)
.offset(y: offset - itemHeight)
}
}
}
enum OffsetPreference: PreferenceKey {
static let defaultValue: CGFloat = 0
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {}
}
enum ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment