Home > Software design >  Scroll to bottom in SwiftUI
Scroll to bottom in SwiftUI

Time:03-05

I want to scroll to the bottom of my scroll view when another comment is added to the chat. I tried using ScrollViewReader but it is not scrolling to the bottom. I'm checking if the comments are adding in the onChange method it is triggering and printing out the last index of the array. I am not sure why it wouldn't be working then

class TakeCommentViewModel: ObservableObject {
    
    @Published var comments = [TakeComment]()
}

in the SwiftUI File:

@ObservedObject var model = TakeCommentViewModel()

var commentsList: some View {
        ScrollViewReader { proxy in
            ScrollView {
                VStack {
                    TakeTopView(dismissAction: dismissAction, take: take)
                    ForEach(model.comments) { comment in
                        TakeCommentView(comment: comment, viewModel: model)
                    }
                }
            }
            .onAppear {
                model.fetchComments(takeID: take.id)
                IQKeyboardManager.shared.enable = false
                proxy.scrollTo(model.comments.count - 1, anchor: .top)
            }
            .onDisappear {
                if model.listener != nil {
                    model.listener.remove()
                }
                IQKeyboardManager.shared.enable = true
            }
            .onChange(of: model.comments.count, perform: { value in
                proxy.scrollTo(model.comments.count - 1)
                let _ = print("CHANGED: \(model.comments.count)")

            })
        }   
    }

CodePudding user response:

Since you are using scrollTo based on index, you need to set index as id.

ForEach(Array(model.comments.enumerated()), id: \.offset) { index, comment in
    TakeCommentView(comment: comment, viewModel: model)
        .id(index)  // ForEach might set id automatically, but I added this just in case
}
  • Related