Show a new View from Button press Swift UI

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")
            }
        }
    }

Leave a Comment