Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change NavigationViewStyle from a descendent view in SwiftUI?

I have a NavigationView at the root of my app that has the initial state of .navigationViewStyle(.stack), but as I navigate, I want to change that style to .doubleColumn.

From my descendent view I have tried calling navigationViewStyle(.doubleColumn) much like how you change the navigation bar title, but no luck.

Trying a ternary operator in the root view also doesn't work navigationViewStyle(isDoubleColumn ? .doubleColumn : .stack)

ROOT VIEW:

var body: some View {
    NavigationView {
        VStack {
            //stuff
        }
    }
    .navigationViewStyle(.stack)
}

Descendent View

var body: some View {
    ScrollView{
        //stuff
    }
    .navigationViewStyle(.doubleColumn) //doesn't work
}
like image 774
A. Lucas Avatar asked Jul 16 '19 14:07

A. Lucas


2 Answers

DoubleColumnNavigationViewStyle is a struct that needs to be initialized. Try it this way:

.navigationViewStyle(DoubleColumnNavigationViewStyle())
like image 170
Khanan Grauer Avatar answered Oct 21 '22 15:10

Khanan Grauer


The code below does the job but with the price of losing of some state data so it may not really be the solution.

struct SwiftUIView: View {

    @State var isDoubleColumn = false

    var body: some View {
        Group {
            if isDoubleColumn{
                NavigationView {
                    Text("Hello, World!")
                }
                .navigationViewStyle(DoubleColumnNavigationViewStyle())
            } else {
                NavigationView {
                    Text("Hello, World!")
                }
            }
        }
    }
}

I'm not an expert but something tells me that the style can't be changed during NavigationView lifetime.

like image 40
Bogdan Timofte Avatar answered Oct 21 '22 14:10

Bogdan Timofte