Search code examples
swiftuiswiftui-navigationlink

NavigationLink inside a ControlGroup


I'm trying to create a series of links within a ControlGroup like so:

ControlGroup {
   NavigationLink(destination: BranchView(branches: mockBranches)) {
      Button("Branches") {
         print("clicked")
      }
   }
   ...
}
  • The button doesn't show any animation and print doesn't run.
  • Replacing the Button element with Text does not fix this.
  • The same code works fine outside the ControlGroup

Google is surprisingly sparse about the combination of the two. I'm beginning to think that I missed something about ControlGroup and it's not intended to be used like this.

Edit:

As noted below, this is due to the migration from NavigationView. See https://developer.apple.com/documentation/swiftui/migrating-to-new-navigation-types


Solution

  • You need to have the NavigationLink inside a NavigationStack for it to work. Also NavigationLink is already a button, so there is no need for the Button("Branches").

    Here is some code that shows NavigationLink working inside a ControlGroup:

    struct ContentView: View {
        var body: some View {
            NavigationStack {
                ControlGroup {
                    NavigationLink(destination: Text("destination")) {
                        Text("tap this link")
                    }
                }
            }
        }
    }