Skip to content

Instantly share code, notes, and snippets.

@jacobsapps
Created April 17, 2025 08:30
Show Gist options
  • Save jacobsapps/24ec919f443a4e15d8c2f1e48feca7be to your computer and use it in GitHub Desktop.
Save jacobsapps/24ec919f443a4e15d8c2f1e48feca7be to your computer and use it in GitHub Desktop.
Font Hacking
import CoreText
func rollFontString(string: String) -> NSAttributedString {
let primaryFont = TextStyle.sfCompact.uiFont
let fallbackFont = UIFont.systemFont(ofSize: 14, weight: .medium)
let attributedString = NSMutableAttributedString(string: string, attributes: [
.kern: 1,
.font: primaryFont,
])
let ctFont = CTFontCreateWithName(primaryFont.fontName as CFString, primaryFont.pointSize, nil)
string.enumerateSubstrings(in: string.startIndex ..< string.endIndex, options: .byComposedCharacterSequences) { substring, substringRange, _, _ in
let uniChar = UniChar(substring.unicodeScalars.first.value)
var glyph: CGGlyph = 0
let hasGlyph = CTFontGetGlyphsForCharacters(ctFont, [uniChar], &glyph, 1)
if !hasGlyph {
attributedString.addAttribute(
.font,
value: fallbackFont,
range: NSRange(substringRange, in: string)
)
}
}
return attributedString
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment