SwiftUI-导航栏颜色更改未应用于状态栏

问题描述 投票:0回答:2

我有以下内容:

var body: some View {
        NavigationView {
            VStack {
                 Text("Hello")
            }.navigationBarTitle("Edit Profile", displayMode: .inline)
             .background(NavigationConfiguration { nc in
                 nc.navigationBar.barTintColor = .red
                 nc.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.black]
            })
        }.navigationViewStyle(StackNavigationViewStyle())
}

对于导航栏的配置,我有:

struct NavigationConfiguration: UIViewControllerRepresentable {
    var configuration: (UINavigationController) -> Void = { _ in }
    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfiguration>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfiguration>) {
        if let nc = uiViewController.navigationController {
            self.configuration(nc)
        }
    }
}

但是由于某些原因,顶部状态栏被忽略了,并且没有应用颜色:

Status bar image

如何将红色也应用于导航栏上方的状态栏,我希望它具有相同的颜色。

我尝试了以下操作,但失败了:

init() {
    UINavigationBar.appearance().backgroundColor = .red
}
swift uinavigationcontroller swiftui uinavigationbar swiftui-navigationlink
2个回答
1
投票
demo

init() { let navBarAppearance = UINavigationBarAppearance() navBarAppearance.configureWithOpaqueBackground() navBarAppearance.backgroundColor = UIColor.systemRed UINavigationBar.appearance().standardAppearance = navBarAppearance }


0
投票
struct NavigationBarModifier: ViewModifier { var backgroundColor: UIColor = .clear init(backgroundColor: UIColor, tintColor: UIColor = .white) { self.backgroundColor = backgroundColor let coloredAppearance = UINavigationBarAppearance() coloredAppearance.backgroundColor = backgroundColor coloredAppearance.titleTextAttributes = [.foregroundColor: UIColor.white] coloredAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white] UINavigationBar.appearance().standardAppearance = coloredAppearance UINavigationBar.appearance().compactAppearance = coloredAppearance UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance UINavigationBar.appearance().tintColor = tintColor } func body(content: Content) -> some View { ZStack{ content VStack { GeometryReader { geometry in Color(self.backgroundColor) .frame(height: geometry.safeAreaInsets.top) .edgesIgnoringSafeArea(.top) Spacer() } } } }}

我在下面的视图中使用它:

struct DummyNavigationView: View {
var body: some View {
    NavigationView {
        VStack {
            NavigationLink(destination: Text("Page 2")) {
                Text("Go to detail")
            }
        }
        .navigationBarTitle("Edit Profile", displayMode: .inline)
    }
    .modifier(NavigationBarModifier(backgroundColor: .red, tintColor: .black))
}}
© www.soinside.com 2019 - 2024. All rights reserved.