[英]Make a list scroll to bottom with SwiftUI
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.我有一个列表,当我插入一个项目时,我希望列表在我的
@ObservedObject
更改时自动滚动到底部。
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 SwiftUI 2.0
Now with Xcode 12 / iOS 14 it can be solved using ScrollViewReader/ScrollViewProxy
in ScrollView
and LazyVStack
(for performance, rows reuse, etc) as follows现在使用 Xcode 12 / iOS 14 可以在
ScrollView
和LazyVStack
使用ScrollViewReader/ScrollViewProxy
解决(为了性能、行重用等),如下所示
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)
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.