Created
December 19, 2023 12:28
-
-
Save ymurao4/ecdd4a5f3036406617607f8b6e5de17d to your computer and use it in GitHub Desktop.
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
struct SampleView: View { | |
@State private var offset: CGFloat = .zero | |
@State var shouldShowStickyView: Bool = true | |
var body: some View { | |
ScrollView { | |
offsetReader | |
VStack { | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
rowView("Foo") | |
} | |
.padding() | |
} | |
.safeAreaInset(edge: .top, spacing: 0) { | |
Text("ヘッダー") | |
.frame(maxWidth: .infinity) | |
.frame(height: 64) | |
.background(Color.white) | |
.offset(y: shouldShowStickyView ? 0 : -64) | |
.opacity(shouldShowStickyView ? 1 : 0) | |
.animation(.easeIn, value: shouldShowStickyView) | |
} | |
.background(Color.gray) | |
.coordinateSpace(name: "scrollViewCoordinateSpace") | |
.onPreferenceChange(ScrollViewOffsetPreferenceKey.self) { | |
if $0 >= 0 { | |
shouldShowStickyView = true | |
} else { | |
shouldShowStickyView = false | |
} | |
} | |
} | |
} | |
extension SampleView { | |
func rowView(_ text: String) -> some View { | |
Text(text) | |
.padding() | |
.frame(maxWidth: .infinity) | |
.background(Color.white) | |
.clipShape(RoundedRectangle(cornerRadius: 10)) | |
} | |
var offsetReader: some View { | |
GeometryReader { proxy in | |
Color.clear | |
.preference ( | |
key: ScrollViewOffsetPreferenceKey.self, | |
value: proxy.frame(in: .named("scrollViewCoordinateSpace")).minY | |
) | |
} | |
.frame (height: 0) | |
} | |
} | |
struct ScrollViewOffsetPreferenceKey: PreferenceKey { | |
static var defaultValue: CGFloat = .zero | |
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment