Home > front end >  How to replace init(destination:tag:selection:label:) with NavigationLink(value:label:) in Swift for
How to replace init(destination:tag:selection:label:) with NavigationLink(value:label:) in Swift for

Time:01-18

I am using the following Swift code to do 2 things in my iPhone app:

  1. Call method somethingElse() when button is clicked
  2. Change view to SecondView()

Code

struct PrimaryView: View {
  @State var buttonSelected: Int? = nil
  
  func onSubmit() {
    somethingElse()
    self.buttonSelected = 1
  }

  var body: some View {
    NavigationStack {
      NavigationLink(destination: SecondView(), tag: 1, selection: $buttonSelected) {
        Button(action: {
          onSubmit()
        }) {
          Text("Click me")
        }
      }
    }
  }
}

This works fine but I get the following warning:

'init(destination:tag:selection:label:)' was deprecated in iOS 16.0: use NavigationLink(value:label:) inside a List within a NavigationStack or NavigationSplitView...

Question: How do I refactor this code so the warning goes away but the functionality stays the same?

CodePudding user response:

If you follow the advice on the warning, you'd get something like this:

NavigationStack {
    List {
        NavigationLink(value: 1) { // use some tag here
            Button(action: {
                onSubmit()
            }) {
                Text("Click me")
            }
        }
    }.navigationDestination(for: Int.self) { _ in 
        // check the closure parameter here to return a different view
        SecondView() 
    }
}

Of course, this will give you a List instead. If you don't want that, the other overload, destinationLink(isPresented:destination:), seems to work. The code is simply

NavigationStack {
    Button(action: {
        onSubmit()
    }) {
        Text("Click me")
    }.navigationDestination(isPresented: $buttonSelected, destination: { SecondView() })
}

With buttonSelected changed to a Bool:

@State var buttonSelected: Bool = false

func somethingElse() {
    print("something Else")
}

func onSubmit() {
    somethingElse()
    self.buttonSelected = true
}
  • Related