1
votes

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.

2
Thank you! I tried it in the .onAppear() modifier.Bohne

2 Answers

4
votes

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!!

1
votes

I got this to work fine.

I store it in the @main struct (iOS 14) which i find cleaner than init() in the View.

extension UINavigationController {
    override open func viewDidLoad() {
        super.viewDidLoad()
        
        let appearance = UINavigationBarAppearance()
        
        appearance.configureWithOpaqueBackground()
        appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        appearance.largeTitleTextAttributes = [.foregroundColor: UIColor  .white]
        
        appearance.largeTitleTextAttributes = [.font : UIFont(name: "OfficinaSans", size: 30)!]
        appearance.titleTextAttributes = [ .font : UIFont(name: "OfficinaSans", size: 20)!]
        appearance.shadowColor = .white
        
        navigationBar.standardAppearance = appearance
        navigationBar.compactAppearance = appearance
        navigationBar.scrollEdgeAppearance = appearance
         
    }
    
}