简体   繁体   中英

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?

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())
        }
    }
}

backup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM