What is the correct way to implement scrolling in a looong list that uses ScrollView and LazyVstack
Imagine I have some api that returns a longs list of comments with replies
The basic usecase is to scroll to the bottom(to the last comment) Most of the time this works fine
But, imagine some of the comments have many replies like 35 or more (or even 300)
User expands replies for the first post, then presses scroll to bottom. The scrollbar reaches the bottom and I see the blank screen. Sometimes the scrollbar may jump for a while before lazyvstack finishes loading or until I manually scroll up a bit or all the way up and down
What should I do in this case? Is this the swiftui performance problem that has no cure?
Abstract example:
ScrollViewReader { proxy in
ScrollView {
LazyVStack {
ForEach(comments) { comment in
CommentView(comment: comment)
.id("comment-\(comment.id)")
}
}
}
}
struct CommentView: View {
let comment: Comment
@State var isExpanded = false
var body: some View {
VStack {
Text(comment.text)
if isExpanded {
RepliesView(replies: comment.replies) // 35-300+ replies
}
}
}
}
...
scroll
proxy.scrollTo("comment-\(lastComment.id)", anchor: .bottom)
You could also consider having your replies be direct children of the LazyVStack. I think the issue you're running into here is that the lazy stack is only lazy for the views in the ForEach, which in your case would be CommentView. Try flattening your CommentView to display the comment text followed by the full list of replies, so that the replies can be inserted lazily as well. That might get you closer to what you're trying to achieve.