【发布时间】:2021-07-02 12:13:23
【问题描述】:
我有一个使用 NavigationLink 的 ForEach 列表,点击时会显示详细视图。 DetailsView 包含一个用于将详细信息保存到数组中的工作表。保存后,工作表被关闭,但导航堆栈上放置了一个额外的 DetailsView,因此我需要点击两次返回链接才能返回列表。
我可能做错了什么,因为我对 swiftui 比较陌生,但无法确定是什么。
感兴趣的三件事:
-
在 ListView 中,我使用 .navigationViewStyle(StackNavigationViewStyle())。删除后,问题就消失了,但 iPad 上的 ListView 变得混乱。
-
我正在使用 insert(at: 0) 在我的数组中添加数据,因为我想要列表顶部的最新数据。如果我改用 append,问题就会消失。想要列表顶部最近保存的项目,我添加了一个排序,但是排序会导致重复问题再次出现。
-
该问题似乎仅在选择列表中创建的第一项(数组中的最后一项)然后将新项保存到数组中时出现。
步骤:
- 首先点击点击此处,然后点击保存,输入名称,然后点击保存。
- 单击标签栏项目已保存。
- 在“已保存项目”列表中单击第 1 步中的列表项目(导航栏应显示“
- 单击保存,输入另一个名称,然后单击保存。此时,复制视图以“
我做错了什么或者我应该做得更好?
xcode 12.4/iOS 14.1
精简代码以重现:
struct TestModel: Identifiable, Codable {
private(set) var id: UUID
var name: String
}
class AppData: ObservableObject {
@Published var testList = [TestModel]()
}
struct NewView: View {
var body: some View {
NavigationView {
NavigationLink(
destination: DetailView(item: TestModel(id: UUID(), name: ""))) {
Text("Tap here first")
}.navigationBarTitle("Main View", displayMode: .inline)
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ListView: View {
@EnvironmentObject var appData: AppData
var body: some View {
NavigationView {
List {
ForEach(appData.testList) { item in
NavigationLink(destination: DetailView(item: item)) {
Text(item.name)
}
}
}
.navigationBarTitle("Saved Items", displayMode: .inline)
}
.navigationViewStyle(StackNavigationViewStyle()) // remove this and issue goes away, but iPad gets "messy".
}
}
struct DetailView: View {
@State private var isSaveShowing = false
@State var item: TestModel
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .center, spacing: 20) {
Text(item.name)
Button(action: {
isSaveShowing = true
}) {
Text("Save".uppercased())
}.sheet(isPresented: $isSaveShowing) {
SaveView(currentItem: item)
}
}
}
}
}
struct SaveView: View {
var currentItem: TestModel
@State private var name = ""
@EnvironmentObject var appData: AppData
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView {
Form {
Section(header: Text("Enter Name ".uppercased())
) {
TextField("Name (required)", text: $name)
}
}
.navigationBarItems(
trailing: Button(action: {
// appData.testList.append(TestModel(id: UUID(), name: name)) // using append instead of insert also resolves issue...
appData.testList.insert(TestModel(id: UUID(), name: name), at: 0)
presentationMode.wrappedValue.dismiss()
}) {
Text("Save")
}
)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView: View {
var appData = AppData()
var body: some View {
TabView {
NewView().tabItem {
Image(systemName: "rectangle.stack.badge.plus")
Text("Calculate")
}
ListView().tabItem {
Image(systemName: "tray.and.arrow.down")
Text("Saved")
}
}
.environmentObject(appData)
}
}
【问题讨论】: