我有一个自定义视图的简单列表。What needs to happen is when one of the items are selected it needs to show the detail view for that item. 在我的代码中,当我第一次选择一个项目时,@Statet selectedListener 没有设置,因此详细视图不会出现。如果我继续选择先前选择的相同项目,则行为保持不变。但是,如果我选择不同的项目,它可以正常工作,我可以返回上一个项目并查看其详细视图而不会出现问题。这是我想做的一件简单的事情,只是无法弄清楚我可能做错了什么。任何帮助,将不胜感激。谢谢你。
struct ListenersListView<Model>: View where Model: ActiveListenerViewModel {
@ObservedObject var viewModel: Model
@State var showDetail = false
@State var selectedListener: UserProfile? = nil
var body: some View {
ScrollView {
VStack(spacing:20) {
ForEach(viewModel.allActiveListeners) { listener in
UserImageSection(listener: listener,
subtext: listener.supportAreas)
.onTapGesture(perform: {
handleTap(listener)
})
}
}
}
.padding(.horizontal,20)
.sheet(isPresented: $showDetail, content: {
if let listener = selectedListener {
ListenerDetailView(listener: listener)
}
else {
// It should never come here but when the first item is selected it does. The only way to not come here is to select another item after the first item has been selected.
Text("Listener not loaded yet")
}
})
}
private func handleTap(_ listener: UserProfile) {
print("Showing listener \(listener.id)")
self.selectedListener = listener
showDetail = true
}
}