Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to present view when clicking on a button?

I'm trying to make an app using Apple's SwiftUI and I need to have two buttons that present two different views in a single List row.

I use Xcode beta 7 and MacOS Catalina beta 7. I've tried to add a Button that present the view but, I couldn't click it and when I tried on a simple Button outside the List and clicked it, the AddList() view didn't appear. I've also tried adding a navigationButton inside navigationButton but it didn't work too. Adding a tapAction doesn't work too when you click on it, the view still does not appear

NavigationView {
            List(0..<5) { item in
                NavigationLink(destination: ContentOfList()) {
                    Text("hello") // dummy text
                    Spacer()
                    Text("edit")
                        .tapAction {
                            AddList() // This is the view I want to present
                    }
                }
                }.navigationBarItems(trailing: NavigationLink(destination: AddList(), label: { // doesn't work within navigationBarItems
                    Image(systemName: "plus.circle.fill")
                }))
        }

I expect the AddList() view to appear but in the two cases, it doesn't.

like image 669
Christophe Prat Avatar asked Jul 02 '19 13:07

Christophe Prat


1 Answers

Much improved version (SwiftUI, iOS 13 beta 7)

The same solution works for dismissing Modals presented with the .sheet modifier.

import SwiftUI

struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
    var body: some View {
        Button(
            "Here is Detail View. Tap to go back.",
            action: { self.presentationMode.wrappedValue.dismiss() }
        )
    }
}

struct RootView: View {
    var body: some View {
        VStack {
            NavigationLink(destination: DetailView())
            { Text("I am Root. Tap for Detail View.") }
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            RootView()
        }
    }
}
like image 81
Chuck H Avatar answered Sep 24 '22 14:09

Chuck H