Created
August 15, 2025 13:48
-
-
Save alexandersandberg/a5e3fc028526c5359a71b96538121716 to your computer and use it in GitHub Desktop.
ScrollToEndButton
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
| // | |
| // ContentView.swift | |
| // ScrollToEndButton | |
| // | |
| // Created by Alexander Sandberg on 15.08.25. | |
| // | |
| import SwiftUI | |
| struct ContentView: View { | |
| private let endID = "END" | |
| private let triggerAtDistanceFromBottom: CGFloat = 100 | |
| @State private var scrolledID: String? | |
| var body: some View { | |
| ScrollView { | |
| VStack { | |
| ForEach(1...20, id: \.self) { _ in | |
| RoundedRectangle(cornerRadius: 3) | |
| .fill(.indigo) | |
| .frame(height: 100) | |
| } | |
| } | |
| .background(alignment: .bottom) { | |
| Color.clear | |
| .id("NOT_END") | |
| .offset(y: -triggerAtDistanceFromBottom * 2) | |
| } | |
| .background(alignment: .bottom) { | |
| Color.clear | |
| .id(endID) | |
| } | |
| .scrollTargetLayout() | |
| } | |
| .contentMargins(16, for: .scrollContent) | |
| .scrollPosition(id: $scrolledID, anchor: .bottom) | |
| .overlay(alignment: .bottom) { | |
| if scrolledID != endID { | |
| Button { | |
| withAnimation { | |
| scrolledID = endID | |
| } | |
| } label: { | |
| Image(systemName: "arrow.down") | |
| .bold() | |
| .foregroundStyle(.white) | |
| .padding() | |
| .background(.ultraThinMaterial, in: .circle) | |
| } | |
| .buttonStyle(.plain) | |
| .transition(.opacity.animation(.spring(duration: 0.2))) | |
| } | |
| } | |
| } | |
| } | |
| #Preview { | |
| ContentView() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment