Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI set navigationViewStyle based on device

I'm trying to get my navigation view style to be stacked on iPad but default on iPhone.

Code:

.navigationViewStyle(UIDevice.current.userInterfaceIdiom == .pad ? StackNavigationViewStyle() : DefaultNavigationViewStyle())

Giving me the error:

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

Are these not both NavigationViewStyle subclasses?

like image 724
stardust4891 Avatar asked Dec 02 '19 18:12

stardust4891


People also ask

What is Stacknavigationviewstyle?

A navigation view style represented by a view stack that only shows a single top view at a time.

How do I navigate from one view to another in SwiftUI?

If you have a navigation view and you want to push a new view onto SwiftUI's navigation stack, you should use NavigationLink .


1 Answers

I recommend to extract it into simple wrapper modifier and use it in place where needed. Here is modifier:

Update:

extension View {
    @ViewBuilder
    public func currentDeviceNavigationViewStyle() -> some View {
        if UIDevice.current.userInterfaceIdiom == .pad {
            self.navigationViewStyle(StackNavigationViewStyle())
        } else {
            self.navigationViewStyle(DefaultNavigationViewStyle())
        }
    }
}

SwiftUI 1.0 (backward-compatible)

extension View {
    public func currentDeviceNavigationViewStyle() -> AnyView {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return AnyView(self.navigationViewStyle(StackNavigationViewStyle()))
        } else {
            return AnyView(self.navigationViewStyle(DefaultNavigationViewStyle()))
        }
    }
}

backup

like image 117
Asperi Avatar answered Sep 27 '22 19:09

Asperi