【问题标题】:Cannot make my status bar color to match my UINavigationBar color in SiwftUI无法使我的状态栏颜色与 SwiftUI 中的导航栏颜色匹配
【发布时间】:2021-01-28 18:07:21
【问题描述】:

我的问题似乎很简单。但我只是花了几个小时寻找解决方案! 我只需要使状态栏的背景颜色符合我的UINavigationBar 背景颜色(本示例中为红色)。

我写了一个最小的代码示例来重现我的问题并帮助你给我一个解决方案......

TestApp.swift

import SwiftUI

@main
struct TestApp: App {
    @Environment(\.scenePhase) private var phase

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: phase) { newPhase in
            switch newPhase {
            case .active:
                UINavigationBar.appearance().backgroundColor = UIColor.red
                break
            default:
                break
            }
        }
    }
}

ContentView.swift

struct DetailView1: View {

    var body: some View {
        Text("Detail view 1")
    }
}

struct ContentView: View {
    @State private var isDisplayDetailView1 = true

    var body: some View {
        NavigationView {
            List {
                Section {
                    NavigationLink(destination: DetailView1(), isActive: $isDisplayDetailView1) {
                        Text("Go to detail view 1")
                    }
                }
            }
            .navigationBarTitle("Menu")
            .listStyle(GroupedListStyle())
        
            DetailView1()
        }
    }
}

显然,我尝试将edgesIgnoringSafeArea(.top) 添加到我的NavigationView 视图(以及ListDetailView1 之一,...),但它并没有改变任何东西...请帮帮我,我不明白问题出在哪里!

【问题讨论】:

    标签: swiftui uinavigationbar statusbar swiftui-navigationview uinavigationbarappearance


    【解决方案1】:

    你使用ScenePhase是有原因的吗

    您可以在file scope添加此代码

    extension UINavigationController {
        override open func viewDidLoad() {
            super.viewDidLoad()
            
            let standard = UINavigationBarAppearance()
            standard.backgroundColor = .blue
            
            let compact = UINavigationBarAppearance()
            compact.backgroundColor = .green
            
            let scrollEdge = UINavigationBarAppearance()
            scrollEdge.backgroundColor = .red
            
            navigationBar.standardAppearance = standard
            navigationBar.compactAppearance = compact
            navigationBar.scrollEdgeAppearance = scrollEdge
        }
    }
    

    【讨论】:

    • 感谢您的回答!我尝试删除我的 onChangecallback 并添加您的代码。结果是:在“菜单”主视图中,条形图都是系统的浅灰色(或白色?)。只有当我滚动到底部时,它才会变成红色(包括边缘)。
    • 示例中没有Menu。尝试不同的设置可能有developer.apple.com/documentation/uikit/uinavigationbaryalantis.com/blog/…
    • 是的,有:第一个主视图(不是真正的屏幕截图,它代表“详细”视图)。好的,我会看到的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多