Skip to content

Instantly share code, notes, and snippets.

@Tricertops
Last active June 14, 2021 08:21
Show Gist options
  • Save Tricertops/2b7c78b91acb34a7c0a4 to your computer and use it in GitHub Desktop.
Save Tricertops/2b7c78b91acb34a7c0a4 to your computer and use it in GitHub Desktop.
UIFont extension to derive new fonts by adding CoreText Font Features, like Proportional Number or Alternate Punctuation.
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!
}
func fontByAddingFeatures(features: [Feature]) -> UIFont {
typealias FeatureDictionary = [String: Int]
let attributes = self.fontDescriptor().fontAttributes()
let attribute: AnyObject! = attributes[UIFontDescriptorFeatureSettingsAttribute]
var featureDictionaries: [FeatureDictionary] = []
if let existingFeatureDictionaries = attribute as? [FeatureDictionary] {
featureDictionaries = existingFeatureDictionaries
}
for feature in features {
featureDictionaries += [
UIFontFeatureTypeIdentifierKey: feature.type,
UIFontFeatureSelectorIdentifierKey: feature.selector,
]
}
let descriptor = self.fontDescriptor().fontDescriptorByAddingAttributes([
UIFontDescriptorFeatureSettingsAttribute: featureDictionaries,
])
return UIFont(descriptor: descriptor, size: 0)
}
}
label.font.fontByAddingFeatures([
UIFont.Features.ProportionalNumbers,
UIFont.Features.AlternatePunctuation,
])
@Tricertops
Copy link
Author

Fixed thanks to @krzyzanowskim.

@junyuan-qi
Copy link

I think featureDictionaries += should use .append now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment