How to make a large title in the navigation controller half light, half bold?

Viewed 93

I want to make my title look like this (1st picture) (day and month are bold (default), year has a light font-weight)
designer's sample

How do I make different styles of font weight in the title in UIKit w/o using Storyboard?
Or may be it is impossible?

I was thinking about creating two UILabel with different styles, but then how do I put them in the title?

2 Answers

Install a UILabel in the navigation item's titleView property.

Install an NSAttributedString into the label's attributedText property. An attributed string can contain text with different styling applied to different parts, like the example you show.

 if let navigationBar = self.navigationController?.navigationBar {

            let frame = CGRect(x: navigationBar.center.x-(navigationBar.center.x/3), y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)
            let myMutableString = NSMutableAttributedString(string: "November 5, 2021", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20)])
            myMutableString.setAttributes([NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20),
                                                   NSAttributedString.Key.foregroundColor: UIColor.black],
                                                  range: NSMakeRange(0, 11))
            let lbl = UILabel(frame: frame)
            lbl.attributedText = myMutableString
            navigationBar.addSubview(lbl)
  }

you can set the center constraints according to your need :)

enter image description here

Related