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?
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() )
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.