SwiftUI set navigationViewStyle based on device
I recommend to extract it into simple wrapper modifier and use it in place where needed. Here is modifier:
extension View {
public func currentDeviceNavigationViewStyle() -> AnyView {
if UIDevice.current.userInterfaceIdiom == .pad {
return AnyView(self.navigationViewStyle(StackNavigationViewStyle()))
} else {
return AnyView(self.navigationViewStyle(DefaultNavigationViewStyle()))
}
}
}
Thats because ? :
should always return values with same type.
You can implement a custom conditional modifier extension like this:
extension View {
public func modify<T, U>(if condition: Bool, then modifierT: T, else modifierU: U) -> some View where T: ViewModifier, U: ViewModifier {
Group {
if condition {
modifier(modifierT)
} else {
modifier(modifierU)
}
}
}
}
Implement custom modifiers like this:
struct IPadNavigationViewStyle: ViewModifier {
func body(content: Content) -> some View { content.navigationViewStyle(StackNavigationViewStyle()) }
}
struct IPhoneNavigationViewStyle: ViewModifier {
func body(content: Content) -> some View { content.navigationViewStyle(DefaultNavigationViewStyle()) }
}
and then use it like:
.modify(if: UIDevice.current.userInterfaceIdiom == .pad, then: IPadNavigationViewStyle(), else: IPhoneNavigationViewStyle() )