我有一个列表,当我插入一个项目时,我希望列表在@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)
}
}
Run Code Online (Sandbox Code Playgroud)
SwiftUI 2.0
现在使用 Xcode 12 / iOS 14 可以使用ScrollViewReader/ScrollViewProxyin ScrollViewand来解决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)
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
752 次 |
| 最近记录: |