我正在尝试使用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)
答案 0 :(得分:0)
您的代码与SwiftUI无关。为了更改UINavigationBar的外观,您必须使用UIKit,它是SwiftUI的前身。下面的代码将全局更改导航栏。
// 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
在 application(_:didFinishLaunchingWithOptions:)方法内的 AppDelegate.swift 文件中调用此方法。此代码适用于 iOS 13 + 。
如果需要,这里是Legacy Customizations的Apple文档。