Tim J
Tim J

Reputation: 1271

Set font for single word in title of UINavigationController

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.

Upvotes: 1

Views: 52

Answers (1)

emrcftci
emrcftci

Reputation: 3514

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

Upvotes: 1

Related Questions