【发布时间】:2020-10-27 12:22:00
【问题描述】:
在我的项目中,我尝试使用 SwiftUI 中的 presentationMode.wrappedValue.dismiss() 在从表单保存数据后弹回上一个视图控制器。
布局是这样的:
根控制器(带有列表视图)--> 列表视图--> 添加新数据 当使用dismiss() 函数时,它总是弹出到根控制器而不是列表视图。
这是我的代码:
根视图控制器:
NavigationView {
List {
Section(header: Text("Sortiert nach \(sortStr)")) {
ForEach(dbModel.players) { player in
NavigationLink(destination: FeedbackListView(player: player)) {
PlayerListItemView(player: player)
}
}// ForEach
.onDelete(perform: delete)
}
} // List
}
反馈列表视图
List {
ForEach(dbModel.feedbacks) { feedback in
FeedbackListItemView(feedback: feedback)
}
.onDelete(perform: delete)
}//List
.listStyle(GroupedListStyle())
.toolbar(content: {
ToolbarItem(placement: .navigationBarTrailing) {
HStack(spacing: 16) {
NavigationLink(destination: AddNewFeedbackView(forPlayer: player)) {
ToolbarPlusButton()
}//Add Button
}
}
}) // Toolbar
添加新反馈视图
Form {
Section(header: Text("Feedback für \(forPlayer.fullName)")) {
TextField("Thema", text: $topic)
}
Section(header: Text("Inhalt")) {
TextEditor(text: $coachingCue)
.frame(minHeight: 120)
}
Section(header: Text("Wichtigkeit")) {
Picker(selection: $rating, label: Text("Wichtigkeit")) {
ForEach(0..<pickerContent.count) {
Text(self.pickerContent[$0])
}
}//Picker
.pickerStyle(SegmentedPickerStyle())
}
Section(header: Text("Datum")) {
DatePicker("", selection: $date, in: ...Date())
.labelsHidden()
}
Section {
Button(action: {
let secondsDate = date.timeIntervalSince1970
let newFeedback = Feedback(id: "", date: secondsDate, player: forPlayer.id!, rating: rating, topic: topic, coachingCue: coachingCue)
dbModel.addFeedback(newFeedback)
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Save")
}
}
}
.navigationBarTitle("Neues Feedback", displayMode: .inline)
点击保存按钮时,我会返回根控制器而不是 FeedbackListView。
【问题讨论】:
-
展示环境变量不是为了这个目的——它只有一个,所以你破坏了完整的导航堆栈。而是使用绑定来链接激活标志以从目标视图停用它。
-
感谢您的澄清!但我仍在努力让它发挥作用。你能给我一个关于如何正确使用它的简短例子吗?我试图在 NavigationLink 中使用“isActive”参数并尝试在 AddNewFeedbackView 中使用 @Binding,但我无法让它工作。
标签: swiftui swiftui-navigationlink