在SwiftUI中,navigationBarTitle
用于设置导航栏的标题。若要定制导航栏标题的颜色,可以通过自定义 UINavigationBarAppearance
来实现。
UINavigationBarAppearance
是一个用于配置导航栏外观的类,包括标题文本颜色、背景颜色、按钮样式等。
UINavigationBarAppearance
的配置。UINavigationBarAppearance
let customNavBarAppearance = UINavigationBarAppearance()
customNavBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.red]
if let navigationController = self.navigationController {
navigationController.navigationBar.standardAppearance = customNavBarAppearance
navigationController.navigationBar.compactAppearance = customNavBarAppearance
navigationController.navigationBar.scrollEdgeAppearance = customNavBarAppearance
}
以下是一个完整的示例,展示如何在 SwiftUI 中为 navigationBarTitle
定制颜色:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("Hello, World!")
.padding()
}
.navigationBarTitle("Custom Title", displayMode: .inline)
.onAppear {
if let navigationController = UIApplication.shared.windows.first?.rootViewController as? UINavigationController {
let customNavBarAppearance = UINavigationBarAppearance()
customNavBarAppearance.titleTextAttributes = [.foregroundColor: UIColor.red]
navigationController.navigationBar.standardAppearance = customNavBarAppearance
navigationController.navigationBar.compactAppearance = customNavBarAppearance
navigationController.navigationBar.scrollEdgeAppearance = customNavBarInspectable
}
}
}
}
}
@main
struct CustomNavBarApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
通过上述步骤和示例代码,你可以轻松地为 SwiftUI 应用的 navigationBarTitle
定制颜色。