我从网络.onAppear 异步加载项目,之后我的 ViewModel 强制重绘 swiftUI 视图。之后我需要滚动列表到特定项目。我这样做了.onRecieve,问题是视图重绘和滚动几乎同时执行,但据我所知,滚动确实先行,所以我需要添加丑陋的黑客延迟,而不是它工作正常。问题是有另一种方法如何在视图刷新后推迟滚动。
struct ItemsListView: View {
@Binding var selectedItem: Item?
@ObservedObject var viewModel: ViewModel
var body: some View {
ScrollViewReader { proxy in
List(viewModel.state.items) { item in
let selected = item.id == selectedItem?.id
self.createCell(item: item, selected: selected)
.onTapGesture {
selectedItem = item
}
}
.listStyle(SidebarListStyle())
.navigationBarTitleDisplayMode(.inline)
.onAppear {
self.viewModel.trigger(.getItems) // triggers async load of items
}
.onReceive(viewModel.$state) { state in
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // hack to give a time redraw ItemsListView
withAnimation {
proxy.scrollTo(selectedItem?.id, anchor: .center)
}
}
}
}
}
查看模型代码,它是真实的,但对于这个主题有点简化
class ViewModel: ObservableObject {
struct State {
var items = [Item]()
}
enum Event {
case getItems
}
func trigger(_ event: Event) {
switch event {
case .getItems: self.getItems()
}
}
@Published var state = State()
init(dataFetcher: RemoteDataProvider) {
self.dataFetcher = dataFetcher
super.init()
}
private func getItems() {
dataFetcher.getItems()
.sink { result in
if case .failure(let err) = result {
print("Retrieving car items list failed:\(err)")
}
} receiveValue: {[weak self] items in
self?.state.items = items
}
.store(in: &subscriptions)
}
}