简体   繁体   English

SwiftUI 视图之间的导航

[英]Navigation between SwiftUI Views

I don't know how to navigate between views with buttons.我不知道如何使用按钮在视图之间导航。

The only thing I've found online is detail view, but I don't want a back button in the top left corner.我在网上找到的唯一东西是详细视图,但我不希望左上角有后退按钮。 I want two independent views connected via two buttons one on the first and one on the second.我想要通过两个按钮连接两个独立视图,一个在第一个,一个在第二个。

In addition, if I were to delete the button on the second view, I should be stuck there, with the only option to going back to the first view being crashing the app.此外,如果我要删除第二个视图上的按钮,我应该会卡在那里,返回第一个视图的唯一选择是让应用程序崩溃。

In storyboard I would just create a button with the action TouchUpInSide() and point to the preferred view controller.在 storyboard 中,我将创建一个带有动作TouchUpInSide()的按钮并指向首选视图 controller。

Also do you think getting into SwiftUI is worth it when you are used to storyboard?当您习惯了 storyboard 时,您还认为进入 SwiftUI 值得吗?

One of the solutions is to have a @State variable in the main view.解决方案之一是在主视图中有一个@State变量。 This view will display one of the child views depending on the value of the @State variable:此视图将根据@State变量的值显示其中一个子视图:

struct ContentView: View {
    @State var showView1 = false

    var body: some View {
        VStack {
            if showView1 {
                SomeView(showView: $showView1)
                    .background(Color.red)
            } else {
                SomeView(showView: $showView1)
                    .background(Color.green)
            }
        }
    }
}

And you pass this variable to its child views where you can modify it:然后将此变量传递给它的子视图,您可以在其中修改它:

struct SomeView: View {
    @Binding var showView: Bool

    var body: some View {
        Button(action: {
            self.showView.toggle()
        }) {
            Text("Switch View")
        }
    }
}

If you want to have more than two views you can make @State var showView1 to be an enum instead of a Bool .如果您想拥有两个以上的视图,您可以将@State var showView1设为enum而不是Bool

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM