How do I change text attributes for a navigation bar title in SwiftUI?

只谈情不闲聊 提交于 2020-01-25 09:24:45

问题


lately, I've been playing around with the new SwiftUI framework.

I do have a basic understanding of how the framework works but I cannot figure out a way to change title attributes for a navigation bar.

I am using the latest Xcode 11 beta 5 and the corresponding swift/swiftUI version

I already tried a few things. First thing I tried was to just add modifiers to a Text, but somehow SwiftUI seems to ignore modifiers in a navigation bar environment.

The second thing I tried was to change the title attributes through UINavigationBar.apperance().titleTextAttributes = ...

but it seems like they removed the ability to customize titleTextAttributes of UINavigationBar in the latest beta version.

//First thing:
List(myData) {
  ...
}
.navigationBarTitle(Text("My title").font(myFont))


// Second thing
UINavigationBar.appearance().titleTextAttributes = myAttrs

I expect the navigation bar title to have my custom font but it's always the apple default font.


回答1:


In SwiftUI, at this point we can not change navigationBarTitle font directly, but you can change navigationBar appearance like this,

struct YourView: View {
    init() {
        //Use this if NavigationBarTitle is with Large Font
        UINavigationBar.appearance().largeTitleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]

        //Use this if NavigationBarTitle is with displayMode = .inline
        //UINavigationBar.appearance().titleTextAttributes = [.font : UIFont(name: "Georgia-Bold", size: 20)!]
    }

    var body: some View {
        NavigationView {
            Text("Hello World!")
              .navigationBarTitle(Text("Dashboard").font(.subheadline), displayMode: .large)
            //.navigationBarTitle (Text("Dashboard"), displayMode: .inline)
        }
    }
}

I hope this will help you. Thanks!!



来源:https://stackoverflow.com/questions/57370107/how-do-i-change-text-attributes-for-a-navigation-bar-title-in-swiftui

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!