Swift: Programmatically make UILabel bold without changing its size?
Asked Answered
B

2

24

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!

Barram answered 12/10, 2016 at 12:52 Comment(3)
Something like that: titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)?Canister
Possible duplicate of How do I set bold and italic on UILabel of iPhone/iPad?Coryden
This may help: How can I get the font size and font name of a UILabel?Schizoid
M
49

Why not just:

titleLabel.font = UIFont.boldSystemFont(ofSize: titleLabel.font.pointSize)
Mazel answered 12/10, 2016 at 12:58 Comment(4)
Thanks! Worked great!Barram
Thanks Works for me.Lim
You are my hero!Unhandsome
If I could upvote 100 times, I would. Thank you.Sekofski
R
18

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)
    }
}
Revulsion answered 12/10, 2016 at 13:11 Comment(1)
Thank you! I went with a different answer but I've learned from your post.Barram

© 2022 - 2024 — McMap. All rights reserved.