I’m currently using the posts to save the scroll position, but is there was way to save the exact scroll position so it stops jumping around and saves precisely.
@State private var lastViewedPostId: String? {
didSet {
if let id = lastViewedPostId {
UserDefaults.standard.set(id, forKey: "lastViewedPostId")
}
}
}
ScrollViewReader { scrollProxy in
ScrollView(showsIndicators: false) {
LazyVStack(spacing: 14) {
if viewModel.posts.count > 0 {
ForEach(sortedPostsForYou) { post in
PostCell(postWithUser: post, appData: appData)
.id(post.id)
.onAppear {
lastViewedPostId = post.id
}
}
.padding(.top, 17)
} else {
LoadingModifier()
.padding(.top, 230)
}
}
}
.tag(0)
.onAppear {
if let savedId = lastViewedPostId {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.02) {
withAnimation(.easeIn) {
scrollProxy.scrollTo(savedId, anchor: .center)
}
}
}
}
}
I tried using the posts but it did not work smoothly.