在这里,我创建了一个可观察对象,并将其添加到环境对象中。在列表行上,单击“我需要更新我的环境对象的某些值”,然后再导航到DetailView。我只是想根据行选择显示对象的详细信息。
这是我尝试的代码:
class MyModel:ObservableObject
{
var selectDate: String
var duration: String
var selectProject: String
init(dateStr: String, durationStr: String, projectName: String) {
self.selectDate = dateStr
self.duration = durationStr
self.selectProject = projectName
}
}
struct ContentView: View {
@EnvironmentObject var model: MyModel
@Environment (\.colorScheme) var colorScheme:ColorScheme
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@ObservedObject var viewModel = TimesheetViewModel()
var body: some View {
List {
ForEach(self.viewModel.tasksArr, id:\.id) { taskObj in
NavigationLink(destination: DetailView()) { >need to update **model** before navigating Detail View
TimeSheetRowView(taskObj:rowElement)
}
}
}
还有其他方法可以执行相同的任务吗?帮帮我
答案 0 :(得分:0)
您可以使用Button
和空的NavigationLink
。点击按钮后,您可以通过编程方式选择一个NavigationLink,但必须先执行以下操作:
@State private var selectedItem: String?
var body: some View {
NavigationView {
List {
ForEach(self.viewModel.tasksArr, id:\.id) { taskObj in
HStack {
Button(action: {
// here you can update your model etc.
self.selectedItem = item
}, label: {
TimeSheetRowView(taskObj:rowElement)
})
NavigationLink(destination: DetailView(), tag: item, selection: self.$selectedItem) {
EmptyView()
}
}
}
}
}
}