SwiftUI 弹出PopupView时如何同步修改内嵌式导航栏遮罩颜色
解决方案
问题原因
你之前直接全局修改UINavigationBar.appearance的背景图,会让当前App所有页面的导航栏永久透明,不符合只在弹窗弹出时给导航栏加遮罩的需求。
实现方案
推荐使用叠加导航栏专属遮罩的方案,兼容性好,不会影响其他页面样式:
- 在当前页面的ZStack最上层,新增一个仅覆盖导航栏区域的半透明层,颜色和弹窗背景遮罩完全一致
- 仅在
showPopup为true时显示该遮罩,同时将弹窗的层级设置高于遮罩,确保弹窗正常展示
完整代码
struct TestView3: View { @State private var showPopup: Bool = true var body: some View { NavigationView { ZStack(alignment: .top) { ScrollView { ForEach(0..<100) { i in Text("text \(i)") } } // 导航栏遮罩,和弹窗背景色完全一致 if showPopup { Color(white: 0, opacity: 0.2) .frame(height: (UIApplication.shared.connectedScenes.first as? UIWindowScene)?.windows.first?.safeAreaInsets.top ?? 0 + 44) .edgesIgnoringSafeArea(.top) .zIndex(1) } BackgroundOverlayView { BasePopupView(titleText: nil, primaryText: "dd", secondaryText: nil, primaryButtonTitle: "aa", primaryButtonAction: { self.showPopup = false }, secondaryButtonTitle: nil, secondaryButtonAction: nil) } .zIndex(2) .hidden(!showPopup) } .navigationBarTitle("title", displayMode: .inline) } } }
iOS 16+ 精简方案
如果只需要适配iOS16及以上系统,可以直接用系统提供的toolbarBackground modifier动态控制导航栏背景,无需额外加遮罩:
struct TestView3: View { @State private var showPopup: Bool = true var body: some View { NavigationStack { // iOS16推荐用NavigationStack代替NavigationView ZStack { ScrollView { ForEach(0..<100) { i in Text("text \(i)") } } BackgroundOverlayView { BasePopupView(titleText: nil, primaryText: "dd", secondaryText: nil, primaryButtonTitle: "aa", primaryButtonAction: { self.showPopup = false }, secondaryButtonTitle: nil, secondaryButtonAction: nil) } .hidden(!showPopup) } .navigationTitle("title") .navigationBarTitleDisplayMode(.inline) // 弹窗弹出时隐藏导航栏背景,即可透出下方的全局遮罩 .toolbarBackground(showPopup ? .hidden : .visible, for: .navigationBar) } } }
内容的提问来源于stack exchange,提问作者Jaekyung You
相关产品推荐
相关产品推荐

