Paul
Paul

Reputation: 125

How can I access a character's alternate font glyph to use in UILabel or UIButton text

I want to use alternate font glyphs in the text of a UILabel. For example, SF Mono has a "0" with no slash. I can see the alternate glyphs in Photoshop, if I use one as a text object and copy/paste it as a character to Xcode, it doesn't paste as the alternate, it pastes as the usual slashed version.

enter image description here

Upvotes: 1

Views: 684

Answers (1)

matt
matt

Reputation: 534935

You aren't going to achieve this using mere copy and paste in Xcode. You're going to have to drop down to the level of core text and do it in code.

In this example, I'm using SFMono to display two zeroes, but one zero has the slash and the other doesn't:

let f = UIFont.monospacedSystemFont(ofSize: 16, weight: .regular)
let desc = f.fontDescriptor
let mas = NSMutableAttributedString(string: "00", attributes: [.font:f])
let d = [
    UIFontDescriptor.FeatureKey.featureIdentifier: kStylisticAlternativesType,
    UIFontDescriptor.FeatureKey.typeIdentifier: kStylisticAltThreeOnSelector
]
let desc2 = desc.addingAttributes([.featureSettings:[d]])
let f2 = UIFont(descriptor: desc2, size: 0)
mas.addAttributes([.font:f2], range: NSRange(location: 1, length: 1))
self.label.attributedText = mas

And here's the resulting label:

enter image description here

Upvotes: 2

Related Questions