iPad 纵向模式下的拆分视图导致在启动时显示无用的视图

Split view on iPad portrait mode results in a useless view being presented on startup

使用以下代码,Useless View 在 iPad 的纵向模式应用程序启动时显示。按一次“后退”按钮会在详细视图中显示“Link 1 个目的地”。只有在第二次按下时才会显示侧边栏。这不是我们想要的几乎所有应用程序的行为。

如果我们从代码中删除无用视图,我们在启动时会得到一个空白屏幕,我们仍然需要按一次后退按钮才能到达 Link 1 目的地,然后按两次后退按钮才能到达边栏。此外,边栏中列表的样式似乎不太理想。

我们想要的行为是 Link1 在应用程序启动时显示目的地,然后按一下“后退”按钮将我们带到边栏。这是我们期望的任何应用程序的完全标准行为,甚至可以使用 SwiftUI 3 吗?

struct ContentView: View {
    @State var selection: Int? = 0
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Link 1", tag: 0, selection: $selection) {
                    Text("Link 1 destination")
                }
                NavigationLink("Link 2", tag: 1, selection: $selection) {
                    Text("Link 2 destination")
                }
            }
            
            //If we delete the Useless View, we still have to press Back twice
            //to get to the sidebar nav.
            Text("Useless View")
                .padding()
        }
    }
}

@Yrb 评论pointed to the right track with tinkering with underlying UIKit UISplitViewController to be forced to show the primary column. However, with somewhat heavy views in the Detail, there is some flashing of the primary column appearing and disappearing on slower iPads. So I did this with the Introspect library:

struct ContentView: View {
    @State var selection: Int? = 0
   
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Link 1", tag: 0, selection: $selection) {
                    Text("Link 1 destination")
                }
                NavigationLink("Link 2", tag: 1, selection: $selection) {
                    Text("Link 2 destination")
                }
            }
            //In my case I never have a 'Nothing Selected' view, you could replace EmptyView() here
            //with a real view if needed.
            EmptyView()
        }
        .introspectSplitViewController { svc in
            if isPortrait { //If it's done in landscape, the primary will be incorrectly disappeared
                svc.show(.primary)
                svc.hide(.primary)
            }
        }
    }
}

这与我们预期的一样,没有闪烁或其他瑕疵。