Home > Software design >  Moving between view controllers using toolbar
Moving between view controllers using toolbar

Time:12-06

This is a beginner question I want to move to the next view controller (OptionsView) when the button in the toolbar tapped, how can I do it?

var body: some View {
        
        NavigationView {
            VStack{
                Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/)
                
            }
            .navigationTitle("Profile")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar{
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    
                    Button {
                        OptionsView()
                    } label: {
                        Label("Settings", systemImage: "gear")
                    }
                }
                
            }
        }
}
    
}

CodePudding user response:

You can use the isActive property of a NavigationLink to programmatically activate the link. The NavigationLink can use EmptyView as it's label so that it's hidden, since you only need it to be activated via the Button.

Then, inside of your Button's action, instead of trying to insert the view (which should always be in the view hierarchy -- not inside an action), you can set the the @State variable to activate.

struct ContentView : View {
    @State private var optionsActive = false
    var body: some View {
        
        NavigationView {
            VStack{
                Text("Hello, World!")
                NavigationLink(isActive: $optionsActive) {
                    OptionsView()
                } label: {
                    EmptyView()
                }
            }
            .navigationTitle("Profile")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar{
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    Button {
                        optionsActive = true
                    } label: {
                        Label("Settings", systemImage: "gear")
                    }
                }
                
            }
        }
    }
}
  • Related