我有一个SwiftUI应用程序,但无法使导航正常工作。凡是接近工作的东西都感觉被黑了。我有一个跟随this tutorial. The slide-out menu looks like this.制作的滑出菜单,当从滑出菜单中选择一个项目时,我还想显示多个视图。 I want it to appear like this.我的菜单有一个类,如下所示。
enum menuItems {
case Subview1
case Subview2
case Subview3
case Subview4
case Subview5
}
class SideMenu: ObservableObject {
@Published var show: Bool = false
@Published var selection: menuItems = menuItems.Events
}
然后我的ContentView如下所示
struct ContentView: View {
@EnvironmentObject var menu: SideMenu
var body: some View {
GeometryReader { geometry in
MainView()
.frame(width: geometry.size.width, height: geometry.size.height)
.offset(x: self.menu.show ? geometry.size.width/2 : 0)
.disabled(self.menu.show ? true : false)
if self.menu.show {
MenuView()
.frame(width: geometry.size.width/2)
.transition(.move(edge: .leading))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct MainView: View {
@EnvironmentObject var menu: SideMenu
var featureDetailView: some View {
switch menu.selection {
case menuItems.Subview1:
return AnyView(Subview1())
case menuItems.Subview2:
return AnyView(Subview2())
case menuItems.Subview3:
return AnyView(Subview3())
case menuItems.Subview4:
return AnyView(Subview4())
case menuItems.Subview5:
return AnyView(Subview5())
}
}
var body: some View {
NavigationView {
featureDetailView
.navigationBarTitle(Text("Subview 1 Title"), displayMode: .inline)
.navigationBarItems(leading: (
Button(action: {
withAnimation {
self.menu.show.toggle()
}
}) {
Image(systemName: "line.horizontal.3")
.imageScale(.large)
.foregroundColor(.white)
}
))
.background(NavigationConfigurator { nc in
nc.navigationBar.barTintColor = .systemBlue
nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
})
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
因此,ContentView负责显示MainView或滑出菜单。然后MainView将基于menu.selection
的值显示正确的子视图。所有这些都有效,但是处理导航时比较麻烦,我想知道是否有更好的方法吗?当显示另一个子视图时,我也无法更改navigationBarTitle。