ios - 如何更改 SwiftUI 中导航栏的背景颜色?

标签 ios swift swiftui

我想更改导航栏的背景颜色。但我做错了什么,颜色看起来如此不同?

enter image description here

我的代码:

UINavigationBar.appearance().backgroundColor = .red

return VStack(spacing: 0) {
    Text("Test")
        .padding(.top, 9.5)
        .padding(.bottom, 8)
        .frame(minWidth: 0, maxWidth: .infinity)
        .background(Color.red)
        .font(.footnote)
    NavigationView {
        Text("Hello")
        .navigationBarTitle(Text("Hi"), displayMode: .inline)
    }
}


编辑:this solution ,情况有所好转,但颜色仍然存在差异。 enter image description here

我现在的代码:

struct ContentView: View {
    var body: some View {
        VStack(spacing: 0) {
            Text("Test")
                .padding(.top, 9.5)
                .padding(.bottom, 8)
                .frame(minWidth: 0, maxWidth: .infinity)
                .background(Color("red")) // Now I use a color set
                .font(.footnote)
            NavigationView {
                Text("Hello")
                .navigationBarTitle(Text("Hi"), displayMode: .inline)
                .background(NavigationConfigurator { nc in
                    nc.navigationBar.barTintColor = UIColor(named: "red") // Now I use a color set
                })
            }
        }
    }
}

struct NavigationConfigurator: UIViewControllerRepresentable {
    var configure: (UINavigationController) -> Void = { _ in }

    func makeUIViewController(context: UIViewControllerRepresentableContext<NavigationConfigurator>) -> UIViewController {
        UIViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavigationConfigurator>) {
        if let nc = uiViewController.navigationController {
            self.configure(nc)
        }
    }
}

最佳答案

iOS 16

您可以使用以下修饰符直接在工具栏项目(例如导航栏)上设置任何颜色:

.toolbarBackground(.red, in: .navigationBar)

Demo


iOS 15 及更低版本

问题出在 UINavigationBarbackgroundImage 上。您应该将其设置为空的 UIImage,例如:

struct ContentView: View {
    
    init() { 
        UINavigationBar.appearance().backgroundColor = .red // Or any other color
        UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
    }
    
    var body: some View {
        ,,,
    }
}

关于ios - 如何更改 SwiftUI 中导航栏的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58822270/

相关文章:

swift - 需要帮助使用 foreach 在 swift ui 中增加数字

ios - Facebook FBSDKAppInviteContent - 缺少应用程序链接 URL

ios - 如何使用自动布局制作均匀间隔的图像行?

ios - 启动参数(NSDoubleLocalizedStrings、NSShowNonLocalizedStrings)不起作用

swift - CompletionHandler 不适用于 UIAlertController 中的闭包

json - 如何在 Swift 中检查我的数组索引是否超出范围

ios - SwiftUI · 后台计时器在模拟器上有效,但在真实设备上无效

ios - obj c 创建一个对象并没有真正起作用,在将几个新对象插入 NSMutuableArray 之后,我总是得到最后插入的对象

ios - 将 nsstring 转换成 pdf 格式然后发送邮件

ios - 可操作的通知不显示操作 Swift 4