Created
April 25, 2023 18:41
-
-
Save 5sw/f1d53ddcf8a194a880144b0905ac9b06 to your computer and use it in GitHub Desktop.
Pinning a view at the bottom of a scroll view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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