Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a new View from Button press Swift UI

Tags:

swiftui

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 seems like everyone is using navigation button within a navigation view, unless im mistaken navigation view is the one that gives me a menu bar right arrows the top of my app so I don't want that. when I put the navigation button in my view that wasn't a child of NavigationView it was just disabled on the UI and I couldn't click it, so I guess I cant use that.

The other examples I have seen seem to use presentation links / buttons which seem to show a sort of pop over view.

Im just looking for how to click a regular button and show another a view full screen just like performing a segue used to in the old way of doing things.

like image 828
AngryDuck Avatar asked Sep 12 '25 17:09

AngryDuck


1 Answers

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")
            }
        }
    }
like image 191
nca Avatar answered Sep 15 '25 09:09

nca