NavigationStack导航栏颜色正常,点击NavigationLink跳转后颜色恢复默认?
问题说明
使用NavigationStack设置了导航栏的蓝色背景和深色配色(让返回按钮等元素显示为白色),但点击NavigationLink跳转到ScanScreen页面后,导航栏恢复成默认样式。新页面未编写任何修改工具栏样式的代码,希望跳转后的页面导航栏仍保持蓝色,返回按钮为白色。
页面效果
- 主页面:导航栏为蓝色,显示标题“SimpleQR”
- 跳转后页面:导航栏恢复默认样式,返回按钮为深色
相关代码
var body: some View { NavigationStack{ VStack{ // 其他视图 // 主体视图 HStack{ NavigationLink(destination: ScanScreen()){ ZStack{ Rectangle() .frame(width: 150, height: 150) .cornerRadius(15) .foregroundColor(Color("LightGray")) VStack{ Image("ScanQRImage") .resizable() .frame(width: 100, height: 100) .cornerRadius(20) Rectangle() .frame(width: 140, height: 2, alignment: .center) .foregroundColor(.gray) .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10)) Text("Scan Code") .bold() } } .padding(EdgeInsets(top: 10, leading: 5, bottom: 10, trailing: 0)) } } }.navigationTitle("SimpleQR") .navigationBarTitleDisplayMode(.inline) .toolbarBackground(Color("AccentColor"), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } }
解决方案
方法1:在子页面显式设置相同样式
直接在ScanScreen的视图中添加和主页面一致的导航栏样式配置:
struct ScanScreen: View { var body: some View { // 你的页面内容,示例: Text("扫描页面") .navigationTitle("扫描") // 可根据需求设置标题,也可省略 .toolbarBackground(Color("AccentColor"), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } }
方法2:封装样式为全局修饰符(推荐)
避免重复编写代码,创建View扩展封装导航栏样式:
extension View { func customNavigationBar() -> some View { self .toolbarBackground(Color("AccentColor"), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar) } }
之后在主页面和子页面调用该修饰符即可:
- 主页面:
VStack{ // ... } .navigationTitle("SimpleQR") .navigationBarTitleDisplayMode(.inline) .customNavigationBar()
- ScanScreen页面:
struct ScanScreen: View { var body: some View { Text("扫描页面") .navigationTitle("扫描") .customNavigationBar() } }
方法3:给整个NavigationStack设置全局样式
如果希望栈内所有页面统一使用该导航栏样式,可直接将样式配置加到NavigationStack上:
NavigationStack{ VStack{ // 主页面内容 } .navigationTitle("SimpleQR") .navigationBarTitleDisplayMode(.inline) } .toolbarBackground(Color("AccentColor"), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .toolbarColorScheme(.dark, for: .navigationBar)
这样所有通过NavigationLink跳转的页面都会自动继承该导航栏样式,无需每个页面单独设置。
原因说明
NavigationStack中每个页面的导航栏样式是独立的,父页面的配置不会自动传递给子页面,必须显式设置或通过全局配置统一应用样式。
内容的提问来源于stack exchange,提问作者ToxicFlame427
相关产品推荐
相关产品推荐

