zoecarver
zoecarver

Reputation: 6403

Transition from one view to another SwiftUI

How can I transition from one View to another? Is there push / pop like in UIKit? Do I have to use a NavigationView and if so how?

Upvotes: 3

Views: 3588

Answers (2)

Evgeny  Lisin
Evgeny Lisin

Reputation: 461

It works for me

struct ContentView : View {
var body : some View {
    NavigationView {
        NavigationLink(destination: DetailView(), label: { Text("To Detail")})
    }
}}

Upvotes: 1

zoecarver
zoecarver

Reputation: 6403

Using a NavigationView

NavigationViews are tied to NavigationButton (AFAIK that is the only way to trigger a segue). Here is a simple example where the main view can transition to a detail view.

struct DetailView : View {
    let value: String

    var body : some View {
        Text("Full View: \(value)")
    }
}

struct MainView : View {
    var body : some View {
        NavigationView {
            NavigationButton(destination: DetailView(value: "Hello World"),
                             label: { Text("Click Me") })
        }
    }
}

This will automatically handle transitions and add a back button.

Using State

Another approach is to use a stateful variable to determine if the child view is displayed. Here is another simple example:

struct DetailView : View {
    let value: String
    let onDone: () -> Void

    var body : some View {
        VStack {
            Text("Full View: \(value)")
            Button(action: onDone, label: { Text("Back") })
        }
    }
}

struct MainView : View {
    @State var displaySubview = false

    var body : some View {
        VStack {
            if displaySubview {
                DetailView(value: "Hello World") {
                    self.displaySubview = false
                }
            } else {
                Button(action: {
                    self.displaySubview = true
                }, label: { Text("Click Me") })
            }
        }
    }
}

This approach requires you to implement more of the UI elements, but it also allows for more control over views.

Upvotes: 3

Related Questions