Swift Changing font programmatically

Viewed 6247

Hi I am currently setting up views below:

func setupViews() {

    self.numberLabel = UILabel(frame: .zero) 
    self.addSubview(self.numberLabel)
    self.numberLabel.snp.makeConstraints { (make) in
        make.edges.equalToSuperview()
    }


    self.numberLabel.textAlignment = .center
    self.numberLabel.textColor = UIColor.white
    self.numberLabel.adjustsFontSizeToFitWidth = true
    self.numberLabel.minimumScaleFactor = 0.5

}

I would like to change the font of the text inside the label to bold font, however it's difficult to see an easy way to do so, following the syntax principles above.

3 Answers

For Swift 5+ and upto latest version (Swift 5.4) period

Stylizing the Font (SystemFont)

UIFont.systemFont(ofSize: 17, weight: .medium)

where you can set .weight provides various UIFont.Weight properties as given below

  • .black
  • .bold
  • .heavy
  • .light
  • .medium
  • .regular
  • .semibold
  • .thin (Looks very cool and I guess Apple also uses this somewhere)
  • .ultralight

Note that it's only for default SystemFont only. AppleDocumentation

Changing the Font

UIFont(name: "HelveticaNeue-Thin", size: 16.0)
  • where name includes the FontName
  • you can also specify .weight by writing - before weight (If that font supports that weight as Not all fontFamily supports all types of UIFont.Weight)
  • This is more preferable method to use for stylising the font if you're not using default SystemFont

You just set the font property of the label, for example:

numberLabel.font = UIFont.systemFont(ofSize: 10, weight: 200)

I'm amazed there's nothing on SO already on this.

Take a look at the reference docs too: https://developer.apple.com/documentation/uikit/uilabel

By the way, unless you are operating within a closure, or other contexts where the semantics are ambiguous (e.g. in an initialiser) you don't generally need to use self. prefix.

Hope that helps.

If your just using the system font you can also do

UIFont.boldSystemFont(ofSize: 16.0)

Selecting whichever size you need

Here's the documentation on it

Related