3.4 C
London
Monday, January 15, 2024

ios – Change NavigationStack title font, tint, and background in SwiftUI


I’m updating the UI of an iOS app, now concentrating on iOS 16 and above.

Within the earlier model of the design I used to be altering the .navigationTitle font, type, and color utilizing one thing like this code:

closing class AppSettings: ObservableObject {
  @Revealed var tint: Colour = .pink {
    didSet { updateNavigationBarAppearance() }
  }

  init() {
    updateNavigationBarAppearance()
  }

  personal func updateNavigationBarAppearance() {
    let look = UINavigationBarAppearance()
    look.configureWithTransparentBackground()
    look.largeTitleTextAttributes = [
      .font: UIFont.preferredFont(forTextStyle: .largeTitle).roundedBold,
      .foregroundColor: UIColor(tint).withAlphaComponent(0.9)
    ]
   look.titleTextAttributes = [
      .font: UIFont.preferredFont(forTextStyle: .headline).roundedBold,
      .foregroundColor: UIColor(tint).withAlphaComponent(0.9)
    ]
    let navBarAppearance = UINavigationBar.look()
    navBarAppearance.standardAppearance = look
    navBarAppearance.compactAppearance = look
    navBarAppearance.scrollEdgeAppearance = look
  }
}

extension UIFont {
  var roundedBold: UIFont {
    guard let descriptor = fontDescriptor
                             .withDesign(.rounded)?
                             .withSymbolicTraits(.traitBold) else { return self }
  return UIFont(descriptor: descriptor, measurement: pointSize)
  }
}

That gave me one thing that appears like this:

Rounded navigation title font and colour

However had the bug of this occurring on scrolled views as we have been utilizing the look.configureWithTransparentBackground(), and transparency would not work within the UINavigationBar.look().backgroundColor configuration.

Scrolled content overlapped

With the OS model bump, we are able to now reap the benefits of utilizing .toolbarBackground which has fastened the transparency challenge when scrolling into the nav space.

Nonetheless, when that modifier is applied it impacts the font of the navigation title, returning it to the default serif face and black/white color.

Does anybody know of a strategy to customise the title whereas additionally utilizing the .toolbarBackground modifier?

Although the .navigationTitle accepts a Textual content component, it appears you can’t customise it, for instance:

  .navigationTitle(
    Textual content("As we speak")
      .font(.system(.largeTitle, design: .rounded, weight: .black))
  )

As you get this warning in Xcode:

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here