Show a new View from Button press Swift UI

前端 未结 2 1432
不知归路
不知归路 2020-12-10 19:11

I would like to be able to show a new view when a button is pressed on one of my views.

From the tutorials I have looked at and other answered questions here it seem

2条回答
  •  温柔的废话
    2020-12-10 19:20

    Possible solutions

    1.if you want to present on top of current view(ex: presentation style in UIKit)

    struct ContentView: View {
        @State var showingDetail = false
    
        var body: some View {
            Button(action: {
                self.showingDetail.toggle()
            }) {
                Text("Show Detail")
            }.sheet(isPresented: $showingDetail) {
                DetailView()
            }
        }
    }
    

    2.if you want to reset current window scene stack(ex:after login show home screen)

    Button(action: goHome) {
        HStack(alignment: .center) {
            Spacer()
            Text("Login").foregroundColor(Color.white).bold()
            Spacer()
        }
    }
    
    func goHome() {
        if let window = UIApplication.shared.windows.first {
            window.rootViewController = UIHostingController(rootView: HomeScreen())
            window.makeKeyAndVisible()
        }
    }
    

    3.push new view (ex: list->detail, navigation controller of UIKit)

    struct ContentView: View {
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink(destination: DetailView()) {
                        Text("Show Detail View")
                    }.navigationBarTitle("Navigation")
                }
            }
        }
    }
    

    4.update the current view based on @state property, (ex:show error message on login failure)

        struct ContentView: View {
            @State var error = true
            var body: some View {
                ...
                ... //login email
                .. //login password
                if error {
                    Text("Failed to login")
                }
            }
        }
    

提交回复
热议问题