Dave
Dave

Reputation: 12206

Set Specific Font Weight for UILabel in Swift

When people have asked how to set a bold font, most people suggest:

let boldFont = UIFont.boldSystemFont(ofSize: ___)

But take a look at all the font weights that the standard system font offers:

Xcode system font weights

So my question is how do you set a light, semibold, or heavy font weight? The only way that I know how is:

sectionLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];

However, I'm still asking because this isn't strongly typed. Most other class attributes are set by selecting from a fixed set of options and don't require passing a string that I could mistype. I guess I could set my own global enum... But any better ideas?

Upvotes: 15

Views: 39242

Answers (5)

CristianMoisei
CristianMoisei

Reputation: 2279

If you want to use system fonts, for Swift 5 a simple extension would look like this:

extension UIFont {
    func withWeight(_ weight: UIFont.Weight) -> UIFont {
        UIFont.systemFont(ofSize: pointSize, weight: weight)
    }
}

Upvotes: 0

arvinq
arvinq

Reputation: 701

You can use this extension. It assigns the weight to the fontDescriptor's weight key and instantiate your font with this new descriptor.

extension UIFont {
  func withWeight(_ weight: UIFont.Weight) -> UIFont {
    let newDescriptor = fontDescriptor.addingAttributes([.traits: [
      UIFontDescriptor.TraitKey.weight: weight]
    ])
    return UIFont(descriptor: newDescriptor, size: pointSize)
  }
}

Upvotes: 18

Krzysztof Skrzynecki
Krzysztof Skrzynecki

Reputation: 2525

The very old thread, but someone may be interested in how to do it in Swift.

UIFont.Weight defines all of the options:

  • ultraLight
  • thin
  • light
  • regular
  • medium
  • semibold
  • bold
  • heavy
  • black

you can use simply like that, e.g.:

label.font = UIFont.systemFont(ofSize: size, weight: .bold)

or if you want to keep the previous size:

label.font = UIFont.systemFont(ofSize: label.font!.pointSize, weight: .bold)

Upvotes: 6

Buhaescu Vlad
Buhaescu Vlad

Reputation: 88

Even more:

let font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight(500))

Upvotes: 2

rmaddy
rmaddy

Reputation: 318804

I couldn't get the UIFontDescriptor to work with the font weight trait but there is another approach.

let font = UIFont.systemFont(ofSize: 20, weight: .light)

Replace .light with whichever value you want from UIFont.Weight which basically matches the dropdown list shown in your question.

Upvotes: 32

Related Questions