使用 SwiftUI 将列表滚动到底部 [英] Make a list scroll to bottom with SwiftUI
本文介绍了使用 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.
有我的实际查看代码:
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 可以使用 ScrollView
和 LazyVStack
中的 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 将列表滚动到底部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文