Last active
June 14, 2021 08:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
label.font.fontByAddingFeatures([ | |
UIFont.Features.ProportionalNumbers, | |
UIFont.Features.AlternatePunctuation, | |
]) |
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
Fixed thanks to @krzyzanowskim.