khyree14
khyree14

Reputation: 31

Q: Navigation without NavigationButton

I am trying to make a navigation menu within my app. Currently when I click the button in the navigation bar, a presentation modal comes up. In that model I have buttons in a list that I unfortunately do not know how to work. Ideally I want the buttons, when clicked, exit the presentation modal, and navigate to a specific view (i.e. if i press "Profile" in the menu I want the "Profile View" to appear). I tried to use a navigation button, but it always shows the back button/ does not exit the presentation modal.

//View with button in nav bar

struct HomeView : View {
    @State var showNav: Bool = false
 var body: some View {
         NavigationView {
            List {
                Text("hi")
                }
                .navigationBarItems(leading:
                    Button(action: {
                        self.showNav = true
                    }) {
                        Image("Image")
                        .resizable()
                            .frame(width: 60, height:60)
                    }
            )
            }.presentation(showNav ? Modal(NavView(),
                                             onDismiss: { self.showNav = false }) : nil)}


//View With navigation controlls
struct NavView : View {

    @State var pressedHome: Bool = false
    @State var pressedProfile: Bool = false




    var body: some View {
            List{

                Button(action: {
                    self.pressedHome = true
                }) {
                    Text("Home")
                }

               Button(action: {
                    self.pressedProflie = true
                }) {
                    Text("Profile")
                }
    }


}

Upvotes: 2

Views: 156

Answers (1)

Hussain Shabbir
Hussain Shabbir

Reputation: 15025

In order to dismiss the presented view add one binding attribute var inside your NavView:-

struct NavView : View {
  @Binding var showNav: Bool
}

And then replace this below line

presentation(showNav ? Modal(NavView(),
                                             onDismiss: { self.showNav = false }) : nil)}

with this

presentation(showNav ? Modal(NavView(showNav: $showNav),
                                             onDismiss: { self.showNav = false }) : nil)}

And then inside your both button actions add this line

Button(action: {
   self.pressedHome = true
   self.showNav.toggle()   //added this line
   }) {
      Text("Home")
  }
Button(action: {
   self.pressedHome = true
   self.showNav.toggle() //added this line
   }) {
      Text("Profile")
  }

Upvotes: 1

Related Questions