Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Forked from Tricertops/UIFont+Features.swift
Last active September 1, 2021 16:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krzyzanowskim/8bc6963895b781632012 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/8bc6963895b781632012 to your computer and use it in GitHub Desktop.
import UIKit
import CoreText
extension UIFont {
typealias Feature = (type: Int, selector: Int)
struct Features {
static var ProportionalNumbers: Feature = (kNumberSpacingType, kProportionalNumbersSelector)
static var AlternatePunctuation: Feature = (kCharacterAlternativesType, 1) // Magic!
// Add more...
}
func fontByAddingFeatures(features: [Feature]) -> UIFont {
// Using Objective-C classes because of some compiler errors...
let attributes = self.fontDescriptor().fontAttributes()
var featureDisctionaries: Array<NSObject> = [];
let attr: AnyObject! = attributes[UIFontDescriptorFeatureSettingsAttribute]
if let existingFeatureDisctionaries = attr as? Array<NSObject> {
featureDisctionaries = existingFeatureDisctionaries;
}
for feature in features {
featureDisctionaries.append([
UIFontFeatureTypeIdentifierKey: feature.type,
UIFontFeatureSelectorIdentifierKey: feature.selector,
])
}
let descriptor = self.fontDescriptor().fontDescriptorByAddingAttributes([
UIFontDescriptorFeatureSettingsAttribute: featureDisctionaries,
])
return UIFont(descriptor: descriptor, size: 0)
}
}
label.font.fontByAddingFeatures([
UIFont.Features.ProportionalNumbers,
UIFont.Features.AlternatePunctuation,
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment