2

I am using a NavigationView with tag/selection initializer that allows controlling the selected detail view both via UI and programmatically, by changing the value of the binding (model.currentItemId):

@EnvironmentObject var model: Model
var items: [Item]

var body: some View {
  NavigationView {
    List {
      ForEach(items) { item in
        NavigationLink(
          tag: item.id,
          selection: $model.currentItemId,
          destination: { ItemView(item: item) },
          label: { ItemPreview(item: item) },
        )
      }
    }
  }
}

It generally works well; now I need to navigate from one detail view (ItemView) to another on the button click:

struct ItemView(): View {
  @EnvironmentObject var model: Model
  var item: Item

  var body: some View {
    // ...
    Button("open") {
      model.currentItemId = 20 // it is in the list, but not on the screen
    }
    // ...
  }
}

and instead of opening the required detail view, it opens the list view.

But if I scroll the list to the item representing the required detail view it would jumps into this detail view without any user action - as soon as this item appears on the screen.

Is there a way to overcome it and open detail view without having the item visible? Or do I have to somehow instruct NavigationView to scroll this item into the view?

Thank you!

esp
  • 7,314
  • 6
  • 49
  • 79
  • 1
    Try to use buttons in list and single navigation link that handles navigation (like in https://stackoverflow.com/a/66904676/12299030). Also it is probably might be needed to use `.isDetailLink(false)` for navigation link. – Asperi Mar 29 '22 at 19:00
  • sorry, that was not the question. I need to navigate to detail view from the button in another detail view of the same list, not from the button in the list. And it works if the link of the target detail view is inside the visible part of the list, it only doesn't work if it is out of screen. – esp Mar 29 '22 at 21:04
  • 1
    What you are asking for is called Programatic Navigation. Asperi gave you a link that shows how to set it up. If you implement it, it will solve your problem. You can also google it for more examples. – Yrb Mar 30 '22 at 00:31

0 Answers0