How to use SF Fonts with attributed text in Interface Builder
I was able to hack my way through it purely in Interface Builder (sort of) by editing the XML directly. Set up your attributed string as you desire, then find the <font />
and edit it as you desire. For example, my button uses the system bold font. Now the font shows up in IB, both in the visual rendering of the attributed string, and in the properties. I can change the size and the bold font is maintained.
<font key="NSFont" size="16" name=".AppleSystemUIFontBold"/>
Here it is in context:
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" lineBreakMode="wordWrap" hasAttributedTitle="YES" translatesAutoresizingMaskIntoConstraints="NO" id="1mt-rM-2b8">
<rect key="frame" x="211" y="8" width="187" height="52"/>
<color key="backgroundColor" red="0.0" green="0.41960784309999999" blue="0.72156862749999995" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<inset key="contentEdgeInsets" minX="4" minY="16" maxX="4" maxY="16"/>
<state key="normal">
<attributedString key="attributedTitle">
<fragment content="Okay, I'll fill it out now">
<attributes>
<color key="NSColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<font key="NSFont" size="16" name=".AppleSystemUIFontBold"/>
</attributes>
</fragment>
</attributedString>
</state>
<connections>
...
</connections>
</button>
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)
}
}