1

I have a UINavigationController that is set with prefersLargeTitles = true

example image

I would like to set the title so that rather than

Discogs | Search Box

it reads

Discogs | Search Box

I cannot see how to set the text via attributed text however.

Is this possible? I am building my view programmatically.

I see a navigationController?.navigationBar.largeTitleTextAttributes property but as that only accepts key/value pairs I do not believe this can be used to apply this effect.

Tim J
  • 1,211
  • 1
  • 14
  • 31
  • There doesn't appear to be a clean solution: https://stackoverflow.com/questions/47255658/large-navigation-bar-text-with-multiple-colors – 10623169 Jul 03 '19 at 10:29

1 Answers1

1

For large title:

You can create custom view (with title label) and set constraints to navigation bar:

customView.widthAnchor.constraint(equalToConstant: 200).isActive = true
customView.heightAnchor.constraint(equalToConstant: 44).isActive = true

self.navigationItem.titleView = customView

For regular title:

You can set custom label to navigationItem's titleView :

let navLabel = UILabel()
let navTitle = NSMutableAttributedString(string: "Discogs", attributes:[
    NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 17.0),
    NSAttributedStringKey.foregroundColor: UIColor.black])

navTitle.append(NSMutableAttributedString(string: " | Search Box", attributes:[
    NSAttributedStringKey.foregroundColor: UIColor.black,
    NSAttributedStringKey.font: UIFont.systemFont(ofSize: 17.0, weight: 
        UIFont.Weight.light)]))

navLabel.attributedText = navTitle
self.navigationItem.titleView = navLabel

Source:

Dushyant Bansal's Medium Article

emrcftci
  • 3,355
  • 3
  • 21
  • 35
  • This is a good solution that answers the question. I would also suggest OP reads the encapsulation of changing font (via a `ChangableFont` protocol) given in this answer: https://stackoverflow.com/a/51443349/10623169. Think it compliments your succinct answer nicely. – 10623169 Jul 03 '19 at 08:39
  • Thanks for your input, I had tried this approach however it does not seem to work when `prefersLargeTitles` is `true` – Tim J Jul 03 '19 at 08:40