如何在iPad和纵向模式下显示SwiftUI的侧边栏



我在iPad上有一个主细节应用程序,当在纵向模式下运行应用程序时,侧边栏是隐藏的。我需要按后退按钮来打开侧边栏。

谁能帮我默认显示侧边栏?我找到了一个答案,建议使用StackNavigationViewStyle当应用程序是在纵向,但随后应用程序看起来像一个巨大的iPhone和消失的主类像一个侧边栏,看起来像一个视图。

这是我的代码。

struct ContentView: View {
var body: some View {
NavigationView {
MyMasterView()
DetailsView()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct MyMasterView: View {
var people = ["Option 1", "Option 2", "Option 3"]
var body: some View {
List {
ForEach(people, id: .self) { person in
NavigationLink(destination: DetailsView()) {
Text(person)
}
}
}
}
}
struct DetailsView: View {
var body: some View {
Text("Hello world")
.font(.largeTitle)
}
}

谢谢

这是可以做到的,但是现在它需要通过uiviewrepresable访问UIKit的UISplitViewController。下面是一个基于这里描述的解决方案的示例。

import SwiftUI
import UIKit
struct UIKitShowSidebar: UIViewRepresentable {
let showSidebar: Bool

func makeUIView(context: Context) -> some UIView {
let uiView = UIView()
if self.showSidebar {
DispatchQueue.main.async { [weak uiView] in
uiView?.next(of: UISplitViewController.self)?
.show(.primary)
}
} else {
DispatchQueue.main.async { [weak uiView] in
uiView?.next(of: UISplitViewController.self)?
.show(.secondary)
}
}
return uiView
}

func updateUIView(_ uiView: UIViewType, context: Context) {
DispatchQueue.main.async { [weak uiView] in
uiView?.next(
of: UISplitViewController.self)?
.show(showSidebar ? .primary : .secondary)
}
}
}
extension UIResponder {
func next<T>(of type: T.Type) -> T? {
guard let nextValue = self.next else {
return nil
}
guard let result = nextValue as? T else {
return nextValue.next(of: type.self)
}
return result
}
}

struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink("Primary view (a.k.a. Sidebar)", destination: DetailView())
}
NothingView()
}
}
}
struct DetailView: View {
var body: some View {
Text("Secondary view (a.k.a Detail)")
}
}
struct NothingView: View {
@State var showSidebar: Bool = false
var body: some View {
Text("Nothing to see")
if UIDevice.current.userInterfaceIdiom == .pad {
UIKitShowSidebar(showSidebar: showSidebar)
.frame(width: 0,height: 0)
.onAppear {
showSidebar = true
}
.onDisappear {
showSidebar = false
}
}
}
}

在iOS 16中,你可以使用columnVisibility

来控制它

最新更新