Last active
August 22, 2018 23:17
-
-
Save foxfriends/6b1dbe25ff127144b4f8d8e6aff45158 to your computer and use it in GitHub Desktop.
Helpers to use UIKit font features in Swift
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 | |
// Usage: | |
// | |
// ``` | |
// UIFont.systemFont(ofSize: 14).usingFeatures([.tabularFigures]) | |
// ``` | |
// | |
extension UIFont { | |
enum Feature { | |
case smallCaps | |
case tabularFigures | |
fileprivate var features: [[UIFontDescriptor.FeatureKey: Int]] { | |
switch self { | |
case .smallCaps: | |
let upperCaseFeature = [ | |
UIFontDescriptor.FeatureKey.featureIdentifier: kUpperCaseType, | |
.typeIdentifier: kUpperCaseSmallCapsSelector, | |
] | |
let lowerCaseFeature = [ | |
UIFontDescriptor.FeatureKey.featureIdentifier: kLowerCaseType, | |
.typeIdentifier: kLowerCaseSmallCapsSelector, | |
] | |
return [upperCaseFeature, lowerCaseFeature] | |
case .tabularFigures: | |
let tabularFigures = [ | |
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType, | |
.typeIdentifier: kMonospacedNumbersSelector, | |
] | |
return [tabularFigures] | |
} | |
} | |
} | |
func usingFeatures(_ features: Set<Feature>) -> UIFont { | |
let descriptor = fontDescriptor.addingAttributes([.featureSettings: features.flatMap { $0.features } ]) | |
return UIFont(descriptor: descriptor, size: pointSize) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment