Ser Pounce
Ser Pounce

Reputation: 14571

is it possible to get NavigationSplitView to work on iPhone when not on root view?

I have an app that utilizes NavigationSplitView on the next view that gets pushed onto the root view's NavigationStack (I don't like using a three column layout and prefer to have an entire screen for my first view). However, in this scenario, NavigationSplitView will not work on the iPhone (I understand that iPhone turns NavigationSplitView into a NavigationStack, but it won't even push the next view on the screen when a NavigationLink is tapped). Here is the full code:

import SwiftUI

struct HomeView: View {
    var body: some View {
        NavigationStack {
            VStack {
                NavigationLink("NextView", destination: NextView())
            }
        }
    }
}

struct NextView: View {
    private let testWorkedString: String = "Test Worked"
    @State private var selectedString: String?
    
    var body: some View {
        NavigationSplitView {
            List(selection: self.$selectedString) {
                NavigationLink("Test", value: self.testWorkedString)
            }
        } detail: {
            if let selectedString = self.selectedString {
                if selectedString == self.testWorkedString {
                    Text(self.testWorkedString)
                }
            }
        }
    }
}

When you tap "Test", it only highlights and doesn't push the next view onto the screen.

My best guess as to why this is happening is because Apple recomends (but doesn't mandate) utilizing NavigationSplitView on the root view. If I make NextView the root view, it works fine on the iPhone. But I was wondering if it's possible there is another reason? I have a work around where I use a NavigationStack instead of NavigationSplitView on iPhone, but I prefer not to do that because I want my app to work on bigger iPhone screens where NavigationSplitView may end up working like an iPad.

Upvotes: 1

Views: 36

Answers (1)

john smith
john smith

Reputation: 117

On iPhone NavigationSplitView does collapse into a NavigationStack but it doesnt seem to navigate properly.

But you could differentiate between iPhone and iPad like this:

@Environment(\.horizontalSizeClass) var horizontalSizeClass

var body: some View {
    if horizontalSizeClass == .compact {
       IphoneView()
    } else {
       IpadView() //use NavigationSplitView here
    }
}

Now you can use NavigationSplitView only when an iPad is used

Upvotes: 0

Related Questions