23

I have a UILabel created programmatically. I would like to make the text of the label bold without specifying font size. So far I have only found:

UIFont.boldSystemFont(ofSize: CGFloat) 

This is what I have exactly:

let titleLabel = UILabel()
let fontSize: CGFloat = 26
titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabelFontSize)

But this way I am also setting the size. I would like to avoid that. Is there a way?

If there is no way, what would be a good workaround in Swift?

Thank you!

user1269290
  • 451
  • 1
  • 6
  • 18
  • Something like that: `titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)`? – Larme Oct 12 '16 at 12:54
  • Possible duplicate of [How do I set bold and italic on UILabel of iPhone/iPad?](http://stackoverflow.com/questions/4713236/how-do-i-set-bold-and-italic-on-uilabel-of-iphone-ipad) – Supratik Majumdar Oct 12 '16 at 12:59
  • This may help: [How can I get the font size and font name of a UILabel?](http://stackoverflow.com/questions/4866138/how-can-i-get-the-font-size-and-font-name-of-a-uilabel) – Ozgur Vatansever Oct 12 '16 at 13:05

2 Answers2

49

Why not just:

titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)
Chris Vig
  • 8,552
  • 2
  • 27
  • 35
17

To just make the Font bold without altering the font size you could create an extension like this (which is based off the answer here:

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor()
        .fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))
        return UIFont(descriptor: descriptor, size: 0)
    }

    func bold() -> UIFont {
        return withTraits(.TraitBold)
    }

}

So that way you could use it like this:

let titleLabel = UILabel()
titleLabel.font = titleLabel.font.bold() //no need to include size!

Update for Swift 4 syntax:

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor               
           .withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))
        return UIFont(descriptor: descriptor!, size: 0)
    }

    func bold() -> UIFont {
        return withTraits(traits: .traitBold)
    }
}
ConfusionTowers
  • 911
  • 11
  • 34
Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27