【问题标题】:SwiftUI Infinite Subview Hierarchy and BreadcrumbsSwiftUI 无限子视图层次结构和面包屑
【发布时间】:2020-09-19 16:37:55
【问题描述】:

我想要实现的是创建一个分层视图。我知道 iOS 根本不喜欢使用面包屑,但我需要从主视图导航到更深的子视图。它们需要嵌套和无限。

您可以在下面的代码和 gif 中看到我到目前为止所做的工作。由于我是初学者开发人员,我不确定这是否是实现这种结构的正确方法(嵌套在子视图中的无限子视图)。此外,当我在视图中导航回来时,添加的按钮(结构 A)消失了。似乎是什么问题?

提前致谢!

code in action gif

import SwiftUI

struct A: View, Identifiable {
    
    @EnvironmentObject var documentB: classB
    
    var id: Int
    var text: String
    var destinationLink: B?
    
    var body: some View {
            NavigationLink(destination: self.destinationLink) {
                VStack{
                    Rectangle()
                        .frame(width: 35, height:25)
                        .background(Color.red)
                    Text("\(text)")
                }
        }
    }
}

struct B: View, Identifiable {
    
    @EnvironmentObject var documentB: classB
    @State var arrayA: [A] = []
    
    var id: Int
    var text: String
    var mainText: String = "Placeholder"
    var body: some View {
        NavigationView {
            VStack {
                Spacer()
                ForEach(arrayA){ item in
                    item
                }
                Spacer()

                Button(action: {
                    let newB = B(id:self.documentB.arrayB.count+1, text:"B \(self.documentB.arrayB.count+1)")
                    self.documentB.arrayB.append(newB)
                    self.arrayA.append(A(id:self.arrayA.count+1, text:"AA \(self.arrayA.count+1)", destinationLink: newB))
                }) {
                    Text("Add A \(self.arrayA.count), B Count: \(self.documentB.arrayB.count)")
                }
            }
            .navigationBarTitle(text)
        }
    }
}

class classB: ObservableObject {
    
    @Published var arrayB: [B] = [B(id:1, text:"MainView")]
    
}

struct ContentView: View {

    @ObservedObject var documentB = classB()

    var body: some View {
            VStack {
                documentB.arrayB[0]
            }
            .environmentObject(documentB)
    }
}

【问题讨论】:

    标签: ios swift navigation swiftui breadcrumbs


    【解决方案1】:

    您只需将NavigationView 移动到ContentView,因为在一个视图层次结构中只需要一个,所以

    struct ContentView: View {
    
        @ObservedObject var documentB = classB()
    
        var body: some View {
            NavigationView {    // << move it here from B
                VStack {
                    documentB.arrayB[0]
                }
            }
            .environmentObject(documentB)
        }
    }
    

    【讨论】:

    • 感谢您的回答。实际上,更困扰我的是这是否是无限子视图的正确结构?因为返回主视图后项目(structA)正在消失。
    • 好吧,因为您使用视图执行此操作,但如果您使用模型执行此操作,该模型保持持久性并基于模型构建视图,那么所有内容都将是持久性的......但那是不同的故事.
    猜你喜欢
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多