本文介绍了使用SwiftUI将列表滚动到底部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,当我插入一个项目时,我想在@ObservedObject更改时自动将列表滚动到底部.

I have a list and when I insert an item, i want to the list to scroll to the bottom automatically when my @ObservedObject changed.

这里是我的实际查看代码:

There is my actual View code :

struct DialogView: View {

    @ObservedObject var viewModel = DialogViewModel()

    var body: some View {
            List {
                ForEach(self.viewModel.discussion, id: \.uuid) {
                    Text($0.content)
                }
            }.animation(Animation.easeOut)


    }
}

推荐答案

SwiftUI 2.0

现在使用Xcode 12/iOS 14,可以使用ScrollViewLazyVStack中的ScrollViewReader/ScrollViewProxy(出于性能,行重用等)解决如下问题

Now with Xcode 12 / iOS 14 it can be solved using ScrollViewReader/ScrollViewProxy in ScrollView and LazyVStack (for performance, rows reuse, etc) as follows

struct DialogView: View {

    @ObservedObject var viewModel = DialogViewModel()

    var body: some View {
        ScrollView {
            ScrollViewReader { sp in
                LazyVStack {
                    ForEach(self.viewModel.discussion, id: \.uuid) {
                        Text($0.content).id($0.uuid)
                    }
                }
                .onReceive(viewModel.$discussion) { _ in
                    guard !viewModel.discussion.isEmpty else { return }

                    withAnimation(Animation.easeInOut) {
                        sp.scrollTo(viewModel.discussion.last!.uuid)
                    }
                }
            }
        }
    }
}

这篇关于使用SwiftUI将列表滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:12