首页 > 解决方案 > 使用 SwiftUI 为 UINavigationBar 自定义背景颜色

问题描述

我正在尝试使用 SwiftUI 为 UINavigationBar 使用我自己的背景颜色,但我无法使用以下代码更改它:

let attrs = [
     NSAttributedString.Key.foregroundColor: UIColor.blue,
     NSAttributedString.Key.font: UIFont(name: "AbrilFatface-Regular", size: 24)!]

UINavigationBar.appearance().titleTextAttributes = attrs
UINavigationBar.appearance().backgroundColor = UIColor(red:253/255, green:213/255, blue:211/255, alpha:1.0)

标签: iosswiftswiftui

解决方案


您的代码与 SwiftUI 无关。要更改 UINavigationBar 外观,您必须使用 SwiftUI 的前身 UIKit。下面的代码将全局更改导航栏。

// Instantiate new UINavigationBarAppearance object
let navigationBarAppearance = UINavigationBarAppearance()
// Set background colour
navigationBarAppearance.backgroundColor = .black
// Set text color for title
navigationBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
// Set text color for large title
navigationBarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

// Assign appearance
UINavigationBar.appearance().standardAppearance = navigationBarAppearance
UINavigationBar.appearance().compactAppearance = navigationBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navigationBarAppearance

AppDelegate.swift文件中调用它 indside application(_:didFinishLaunchingWithOptions:)方法。此代码适用于iOS 13+

如果您需要,这里是旧版自定义的苹果文档。


推荐阅读