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)")
})
}
}
ScrollViewReaderprobably expects anid. Does it work if you doif let last = model.comments.last { proxy.scrollTo(last.id) }?id, thescrollTousesidnotindex, so you may want to addidafterTakeTopView(dismissAction: dismissAction, take: take)and try againForEachwill append theidautomatically