1

[1 SOLUTION FOUND!] Thanks to George's comment I was able to find a solution https://stackoverflow.com/a/70353393/882987 but if somebody has any other solution feel free to write it :)

I am having some issues with setting custom navigation bar tint color in SwiftUI for "pushed" views.

Code is something like this, having a stack of items and tapping on each of them we show/push some detail view:

NavigationView {
        ScrollView {
            LazyVStack(alignment: .leading) {
                ForEach(items) { item in
                    NavigationLink(destination: DetailItemView(item))) {
                        ListItemView(item)
                    }
                }
            }
        }
    }

And I would like to have different navigation bar tint color for each view that gets pushed.

Is there a way to achieve that?

BSevo
  • 743
  • 5
  • 13
  • [This](https://stackoverflow.com/a/69227009/9607863) should help – George Dec 14 '21 at 17:19
  • @George are you sure? The destination View does not have NavigationView in its body, it is pushed. Is there some way to check in SwiftUI View if it is in navigation? – BSevo Dec 14 '21 at 17:23
  • 1
    Oh yeah, missed that. You can still use the solution - maybe you could pass down a `Binding` of the color you want it to be to the destination? Then in the `init` of the destination view, you set that binding? You can keep passing the binding down as far as needed. Although I wonder if an environment object may work better and look cleaner. – George Dec 14 '21 at 17:25
  • @George I will try with Binding now, tnx – BSevo Dec 14 '21 at 17:26
  • Awesome, tnx @George I used basic Binding and it works, I will post the answer :) – BSevo Dec 14 '21 at 17:40

1 Answers1

0

Thanks to George's comments I was able to find a solution, using basic Binding.

In the view A I added:

@State private var navColor = Color.primary

and I added the modifier:

NavigationView {
...
}
.accentColor(navColor)

And in view B I added:

@Binding var navColor: Color

So I can change the navColor property to anything I want in view B and it will update the accentColor (and with that the navigation bar tint color)

BSevo
  • 743
  • 5
  • 13