如何设置DocumentGroup的工具栏背景为可见状态?
解决DocumentGroup导航栏背景可见性问题
问题核心
DocumentGroup自带的导航栏属于Scene层级,SwiftUI的toolbarBackground和toolbarBackgroundVisibility修饰符默认作用于View层级的导航栏(比如NavigationStack内的导航栏),因此直接在ContentView中添加这些修饰符无法影响DocumentGroup的原生导航栏。
方案一:不引入NavigationStack,直接修改DocumentGroup导航栏外观
通过UIKit的外观配置,直接修改DocumentGroup导航栏的背景样式,无需额外嵌套NavigationStack:
struct ToolbarTestApp: App { init() { // 创建导航栏外观配置 let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() // 设置不透明背景 navBarAppearance.backgroundColor = .systemBackground // 匹配SwiftUI的.bar颜色,可自定义 // 应用到标准和滚动边缘状态的导航栏 UINavigationBar.appearance().standardAppearance = navBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance } var body: some Scene { DocumentGroup(newDocument: ToolbarTestDocument()) { file in ContentView(document: file.$document) } } }
配置完成后,DocumentGroup的原生导航栏会显示背景,ContentView中添加的toolbar按钮也能正常工作。
方案二:使用NavigationStack并避免双导航栏
如果需要用NavigationStack管理导航逻辑,只需隐藏DocumentGroup的原生导航栏即可:
struct ToolbarTestApp: App { var body: some Scene { DocumentGroup(newDocument: ToolbarTestDocument()) { file in NavigationStack { ContentView(document: file.$document) .toolbar { Button { showInspector.toggle() } label: { Label("Show inspector", systemImage: "sidebar.trailing") } } .toolbarBackground(.bar, for: .navigationBar) .toolbarBackgroundVisibility(.visible, for: .navigationBar) } .navigationBarHidden(true) // 隐藏DocumentGroup的原生导航栏 } } }
此时所有toolbar相关修饰符都会作用于自定义的NavigationStack导航栏,不会出现双栏重叠问题。
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

