SwiftUI中列表滑到导航栏下方时如何去除叠加层保持导航栏常黑
问题原因
你当前的NavigationBarModifier仅对顶部安全区域填充了指定颜色,没有修改系统导航栏的默认半透明磨砂属性。当列表滑动到导航栏下方时,系统自带的半透明磨砂效果会叠加在你设置的黑色背景上,最终呈现为灰色。
修复方案
你可以通过统一配置UINavigationBar的全局外观,显式指定导航栏常规状态、滚动边缘状态的背景样式,彻底关闭磨砂效果,让导航栏始终显示纯黑色,同时不影响你后续动态修改颜色的逻辑。
修改后的完整代码
import SwiftUI struct NavigationBarModifier: ViewModifier { var backgroundColor: Binding<Color> init(backgroundColor: Binding<Color>) { self.backgroundColor = backgroundColor // 配置导航栏全局外观,关闭半透明效果 let appearance = UINavigationBarAppearance() appearance.configureWithOpaqueBackground() appearance.shadowColor = .clear // 不需要导航栏底部分割线可删除该行 UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance } func body(content: Content) -> some View { ZStack{ content VStack { GeometryReader { geometry in self.backgroundColor.wrappedValue .frame(height: geometry.safeAreaInsets.top) .edgesIgnoringSafeArea(.top) Spacer() } } } } } extension View { func navigationBarColor(_ bgColor: Binding<Color>) -> some View { self.modifier(NavigationBarModifier(backgroundColor: bgColor)) } } struct ContentView: View { @State private var bgColor: Color = .black var body: some View { NavigationView { List { Button { } label: { Text("Button") } Button { } label: { Text("Button") } Button { } label: { Text("Button") } } .navigationBarTitle("", displayMode: .inline) .navigationBarColor(self.$bgColor) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
适配iOS 16+简化写法
如果你的项目最低支持iOS 16,也可以直接用SwiftUI原生toolbarBackground modifier替代自定义Modifier,写法更简洁:
struct ContentView: View { @State private var bgColor: Color = .black var body: some View { NavigationStack { List { Button { } label: { Text("Button") } Button { } label: { Text("Button") } Button { } label: { Text("Button") } } .toolbarBackground(bgColor, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) } } }
内容的提问来源于stack exchange,提问作者Degtiarev Aleksei
相关产品推荐
相关产品推荐

