SwiftUI 更新导航栏标题颜色 [英] SwiftUI update navigation bar title color
问题描述
如何在 SwiftUI 中更改导航栏标题颜色
How to change the navigation bar title color in SwiftUI
NavigationView {
List{
ForEach(0..<15) { item in
HStack {
Text("Apple")
.font(.headline)
.fontWeight(.medium)
.color(.orange)
.lineLimit(1)
.multilineTextAlignment(.center)
.padding(.leading)
.frame(width: 125, height: nil)
Text("Apple Infinite Loop. Address: One Infinite Loop Cupertino, CA 95014 (408) 606-5775 ")
.font(.subheadline)
.fontWeight(.regular)
.multilineTextAlignment(.leading)
.lineLimit(nil)
}
}
}
.navigationBarTitle(Text("TEST")).navigationBarHidden(false).foregroundColor(.orange)
}
我尝试过 .foregroundColor(.orange)
但它不起作用
I have tried with .foregroundColor(.orange)
but it is not working
也试过 .navigationBarTitle(Text("TEST").color(.orange))
有什么帮助吗?
推荐答案
不必使用 .appearance()
来全局执行此操作.
It is not necessary to use .appearance()
to do this globally.
虽然 SwiftUI 不直接公开导航样式,但您可以使用 UIViewControllerRepresentable
解决这个问题.由于 SwiftUI 在幕后使用常规的 UINavigationController
,视图控制器仍将具有有效的 .navigationController
属性.
Although SwiftUI does not expose navigation styling directly, you can work around that by using UIViewControllerRepresentable
. Since SwiftUI is using a regular UINavigationController
behind the scenes, the view controller will still have a valid .navigationController
property.
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)
}
}
}
并使用它
struct ContentView: View {
var body: some View {
NavigationView {
ScrollView {
Text("Don't use .appearance()!")
}
.navigationBarTitle("Try it!", displayMode: .inline)
.background(NavigationConfigurator { nc in
nc.navigationBar.barTintColor = .blue
nc.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.white]
})
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
这篇关于SwiftUI 更新导航栏标题颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!