SwiftUI中

时间:2019-12-30 08:15:00

标签: swift uinavigationcontroller swiftui navigationlink

与SwiftUI中Push的{​​{1}}和Pop等效吗?

1 个答案:

答案 0 :(得分:1)

根:

window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(Model()))

iOS版本13.1:

class Model: ObservableObject {
    @Published var pushed = false
}

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        NavigationView {
            VStack {
                Button("Push") {
                    self.model.pushed = true
                }

                NavigationLink(destination: DetailView(), isActive: $model.pushed) { EmptyView() }
            }
        }
    }
}

struct DetailView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        Button("Bring me Back") {
            self.model.pushed = false
        }
    }
}

删除默认的后退按钮并添加我们自己的按钮,将使我们得以解决,直到该错误被Apple修复为止。

class Model: ObservableObject {
    @Published var pushed = false
}

struct ContentView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        NavigationView {
            VStack {
                Button("Push") {
                    self.model.pushed = true
                }

                NavigationLink(destination: DetailView(), isActive: $model.pushed) { EmptyView() }
            }
        }
    }
}

struct DetailView: View {
    @EnvironmentObject var model: Model

    var body: some View {
        Button("Bring me Back") {
            self.model.pushed = false
        }
        .navigationBarBackButtonHidden(true)
        .navigationBarItems(leading: MyBackButton(label: "Back!") {
            self.model.pushed = false
        })
    }
}

struct MyBackButton: View {
    let label: String
    let closure: () -> ()

    var body: some View {
        Button(action: { self.closure() }) {
            HStack {
                Image(systemName: "chevron.left")
                Text(label)
            }
        }
    }
}

more to refer