swiftui - SwiftUI presentationMode.wrappedValue.dismiss() 弹回根目录
问题描述
在我的项目中,我试图在 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)
当点击保存按钮时,我会返回根控制器而不是反馈列表视图。
解决方案
我正在经历同样的事情。问题的根源是因为NavigationLink
toAddNewFeedbackView
在一个ToolbarItem
. 为什么这是个问题?我不知道。
但在知道这一点后,我发现了以下https://www.hackingwithswift.com/forums/swiftui/unexpected-behaviour-with-toolbar-and-navigation-bar/4893。在这里它指出,一旦您将以下导航视图样式放在您的NavigationView
上面,它就会得到解决。
.navigationViewStyle(StackNavigationViewStyle())
因此,在您的示例中,它将导致:
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
}
.navigationViewStyle(StackNavigationViewStyle())
推荐阅读
- c - 如何清理由“out”指针参数创建的分配结构?
- relayjs - 将片段组合到查询中时无法使用`useLazyLoadQuery`获取正确的数据
- kotlin - 递归类型检查在 Kotlin 中是如何工作的?
- java - Android 多重微调器
- python - Redis 发布在 Flask 路由中不起作用
- javascript - 为什么 fs.js 返回 [object Object] 并关闭我的机器人?
- python - Pandas - 计算每个系列中的元素数量
- python - Django“order_by”不包括第一项
- python - 使用字典提高算法效率
- c# - 如何在 C# 中将属性作为参数传递?