我有一个列表,当我插入一个项目时,我想在@ObservedObject
更改后,列表自动滚动到底部。
有我实际的查看代码:
struct DialogView: View {
@ObservedObject var viewModel = DialogViewModel()
var body: some View {
List {
ForEach(self.viewModel.discussion, id: \.uuid) {
Text($0.content)
}
}.animation(Animation.easeOut)
}
}
答案 0 :(得分:1)
SwiftUI 2.0
现在,使用Xcode 12 / iOS 14可以使用ScrollViewReader/ScrollViewProxy
和ScrollView
中的LazyVStack
(出于性能,行重用等)解决问题
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)
}
}
}
}
}
}