Last active
March 4, 2022 11:54
-
-
Save niaeashes/d8f7f17c56f2ccd444032b0145b62283 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 SizeKey: PreferenceKey { | |
| static var defaultValue: CGSize = .zero | |
| static func reduce(value: inout CGSize, nextValue: () -> CGSize) { | |
| value = nextValue() | |
| } | |
| } | |
| struct OffsetKey: PreferenceKey { | |
| static var defaultValue: CGFloat = .zero | |
| static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { | |
| value = nextValue() | |
| } | |
| } | |
| struct ContentView: View { | |
| @State var size: CGSize? = nil | |
| @State var showOverlay = false | |
| @State var offset: CGFloat = .zero | |
| @Namespace var scrollId | |
| var body: some View { | |
| ScrollView { | |
| ZStack { | |
| VStack { | |
| GeometryReader { geometry in | |
| Button(action: { withAnimation { showOverlay.toggle() } }) { | |
| Text("Hello, world!") | |
| .padding() | |
| .compositingGroup() | |
| } | |
| .background(GeometryReader { geometry in | |
| Color.clear | |
| .preference(key: SizeKey.self, value: geometry.size) | |
| .onPreferenceChange(SizeKey.self) { size = $0 } | |
| }) | |
| } | |
| .frame(width: size?.width, height: size?.height) | |
| .border(Color.red) | |
| .overlay(OverlayView().opacity(showOverlay ? 1.0 : 0).offset(x: 0, y: -(size?.height ?? 0) - 16)) | |
| ForEach(0..<30, id: \.self) { i in Text("No.\(i)").padding() } | |
| } | |
| GeometryReader { geometry in | |
| Color.clear.preference(key: OffsetKey.self, value: geometry.frame(in: .named(scrollId)).minY) | |
| } | |
| .frame(height: 0) | |
| } | |
| } | |
| .coordinateSpace(name: scrollId) | |
| .onPreferenceChange(OffsetKey.self) { | |
| offset = $0 | |
| print(Date(), "Change offset!!!") | |
| } | |
| } | |
| } | |
| struct OverlayView: View { | |
| var body: some View { | |
| Button(action: { print("Tap!!!") }) { | |
| Text("Tap") | |
| .padding() | |
| } | |
| .clipShape(Capsule()) | |
| .contentShape(Capsule()) | |
| .overlay(Capsule().stroke(Color.accentColor, lineWidth: 2)) | |
| } | |
| } | |
| struct 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