在 SwiftUI 中滚动到底部

Scroll to bottom in SwiftUI

我想在聊天中添加其他评论时滚动到滚动视图的底部。我尝试使用 ScrollViewReader 但它没有滚动到底部。我正在检查注释是否添加到它触发的 onChange 方法中并打印出数组的最后一个索引。我不确定为什么那时它不起作用

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

在 SwiftUI 文件中:

@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)")

            })
        }   
    }

由于您使用的是基于索引的scrollTo,您需要将索引设置为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
}