koleS
koleS

Reputation: 1313

SwiftUI switch between NavigationViewStyles

I want to present a nested list of lists either as a tree or as a grid. While the tree looks good in the split view on iPad, the grid is too big to fit.

Thus I would like to present this view using the StackNavigationViewStyle when in the grid display mode and using the DefaultNavigationViewStyle when in the tree display mode.

I have a toggle showList to store the mode and I want to use at as follows to switch to navigation view style:

.navigationViewStyle(self.showList ? DefaultNavigationViewStyle() : StackNavigationViewStyle())

But the compiler complains that:

Result values in '? :' expression have mismatching types 'DefaultNavigationViewStyle' and 'StackNavigationViewStyle'

even though both inherit from NavigationViewStyle.

Is it even possible to switch between navigation view styles or is it that once I pick one I have to stick to it in that view?

Upvotes: 1

Views: 535

Answers (1)

Asperi
Asperi

Reputation: 257711

You cannot use ternary operator in navigationViewStyle modifier, because styles have different types, but you can use custom modifier like the following

extension NavigationView {
    @ViewBuilder
    func switchStyle(if flag: Bool) -> some View {
        if flag {
            self.navigationViewStyle(DefaultNavigationViewStyle())
        } else {
            self.navigationViewStyle(StackNavigationViewStyle())
        }
    }
}

Upvotes: 3

Related Questions