Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use SF Fonts with attributed text in Interface Builder

I'm on Xcode 9.x and I want to use attributed text on a UILabel (in InterfaceBuilder).

I want to set : System font (San Fracisco) and some words in bold style. But it doesn't work (italic works but not bold ...).

I can't choose System font (San Francisco Pro/Display) unless I import all San Francisco fonts in Xcode project (but it's very Heavy : 15Mb ! )

How do you make it work please ? Thx.

like image 587
QLag Avatar asked Dec 01 '17 13:12

QLag


People also ask

How to add fonts in info plist?

To do this, add the key "Fonts provided by application" to Info. plist (the raw key name is UIAppFonts ). Xcode creates an array value for the key; add the name of the font file as an item of the array. Be sure to include the file extension as part of the name.

How to add custom fonts into Xcode?

Add the font file to your Xcode project Select File menu > Add Files to "Your Project Name"... from the menu bar, select all the fonts you need to add, then click the Add button. Or drag the file from Finder and drop it into your Xcode project. Drag the font files from Finder and drop it into your Xcode project.

How do I set the font family in Swift?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.


1 Answers

As far as I know you cannot do it strictly within Interface Builder.

But if you are subclassing the enclosing view, or the label view itself, you can easily reset the font face in awakeFromNib() while still retaining the rest of the setup from Interface Builder for the label. That will save you creating it entirely from scratch programmatically.

Set up the label in IB as usual, including attributes, constraints, actions. Use an arbitrary font for previewing. Make sure you Ctrl-drag an outlet for the styled label, then use code as below to switch the font in awakeFromNib. When your app runs it will use the system font, along with all the attributes, position constraints, etc. you already established in IB.

[Edit: Corrected to add bold font weight, which won't get carried over from IB.]

For instance:

class EnclosingViewSubclass : UIView {

    // The outlet you create for the label
    @IBOutlet weak var styledLabel: UILabel!

    // ...

    override func awakeFromNib() {
        super.awakeFromNib()

        // setting the label's font face to the system font, including picking
        // up the font-size you establish in InterfaceBuilder
        styledLabel.font = UIFont.systemFont(ofSize: styledLabel.font.pointSize, 
                                             weight: UIFontWeightBold)
    }
}
like image 137
Jason Campbell Avatar answered Oct 24 '22 10:10

Jason Campbell