Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Changing font programmatically

Tags:

ios

swift

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.

like image 744
rb2030 Avatar asked Sep 13 '25 21:09

rb2030


2 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
like image 97
Nayan Dave Avatar answered Sep 16 '25 12:09

Nayan Dave


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.

like image 27
Marcus Avatar answered Sep 16 '25 11:09

Marcus