在 SwiftUI 5 中 UINavigationBar.appearance().titleTextAttributes 不起作用。您需要使用以下方法之一来更改标题中的字体:
init () {
UINavigationBar.appearance().largeTitleTextAttributes = [.font : UIFont(name: "Georgia", size: 20)!]
// OR
UINavigationBar.appearance().largeTitleTextAttributes = [.font:UIFont.preferredFont(forTextStyle:.text-style)]
}
.text-style 可以在 UIFont.TextStyle 文档中找到,例如
.caption
.body
.title1
.title2
.title3
etc
更新 1(回答有关 cmets 中确切代码的问题)
struct ContentView: View {
init () {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
UINavigationBar.appearance().largeTitleTextAttributes = [.font:UIFont.preferredFont(forTextStyle:.title2),
.foregroundColor:UIColor.systemBlue,
.paragraphStyle: paragraph
]
...
然后在体内我有这个。您可能应该注意 displayMode 参数
// Body is in the same ContentView struct. Settings from init will be used in navigationBarTitle
// listView() is just a custom function returning a SwiftUI's List()
var body: some View {
NavigationView {
listView()
.navigationBarTitle(
Text(self.accts.selCount <= 0 ? "Accounts" : "\(self.accts.selCount) selected")
,
displayMode:.large)