Home > OS >  SwiftUI NavigationView vs NavigationStack for iOS 15/16
SwiftUI NavigationView vs NavigationStack for iOS 15/16

Time:09-13

I'm trying to make my iPhone apps (targeting iOS 15 and above) fully compatible with iOS 16 without success!

I don't know how to have NavigationView for iOS 15 and NavigationStack for iOS 16 in the same piece of code.

The code above isn't accepted by Xcode:

if #available(iOS 16, *) {
   NavigationStack {
} else {
   NavigationView {
}

From: SwiftUI NavigationView/Stack if available iOS 15/16

I guess that creating a custom container, as suggested by @timmy, will be the only solution. But I don't know how to proceed.

What's the solution then?

CodePudding user response:

Personally I wouldn't use NavigationStack unless I would target iOS 16 but if you want to do that you could make your own Navigation Wrapper

struct MyNavigation<Content>: View where Content: View {
    @ViewBuilder var content: () -> Content
    
    var body: some View {
        if #available(iOS 16, *) {
            NavigationStack(root: content)
        } else {
            NavigationView(content: content)
        }
    }
}

and then just use it, like you would NavigationStack or NavigationView and on iOS 15 or older it would use NavigationView and on iOS 16 or newer it would use NavigationStack

Your code isn't accepted by Xcode because it isn't valid. You cannot have a { without a } in the same block.

  • Related