Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active October 9, 2017 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimpiax/0fddf0c01477e843072450707c225891 to your computer and use it in GitHub Desktop.
Save dimpiax/0fddf0c01477e843072450707c225891 to your computer and use it in GitHub Desktop.
UIFont's extension which serves FontDescriptor attributes
//
// UIFont+.swift
// Autofriend
//
// Created by Pilipenko Dima on 10/9/17.
// Copyright © 2017 dimpiax. All rights reserved.
//
import Foundation
import UIKit
private typealias FeatureType = [UIFontDescriptor.FeatureKey: Int]
extension UIFont {
func addFeatures(_ value: FeatureOptions) -> UIFont {
var features = [FeatureType]()
let applyExistFeature = { (option: FeatureOptions) in
guard value.contains(option) else { return }
guard let feature = option.getFeature() else {
print("Option for \(option.rawValue) are not served")
return
}
features.append(feature)
}
applyExistFeature(.lowerSmallCaps)
applyExistFeature(.upperSmallCaps)
applyExistFeature(.stylisticAltSixOn)
let descriptor = fontDescriptor.addingAttributes([.featureSettings: features])
return UIFont(descriptor: descriptor, size: descriptor.pointSize)
}
}
struct FeatureOptions: OptionSet {
let rawValue: Int
static let lowerSmallCaps = FeatureOptions(rawValue: 1 << 0)
static let upperSmallCaps = FeatureOptions(rawValue: 1 << 1)
static let stylisticAltSixOn = FeatureOptions(rawValue: 1 << 2)
static let all: FeatureOptions = [.lowerSmallCaps, .upperSmallCaps, .stylisticAltSixOn]
fileprivate func getFeature() -> FeatureType? {
switch rawValue {
case FeatureOptions.lowerSmallCaps.rawValue:
return buildFeature(identifier: kLowerCaseType, type: kLowerCaseSmallCapsSelector)
case FeatureOptions.upperSmallCaps.rawValue:
return buildFeature(identifier: kUpperCaseType, type: kUpperCaseSmallCapsSelector)
case FeatureOptions.stylisticAltSixOn.rawValue:
return buildFeature(identifier: kStylisticAlternativesType, type: kStylisticAltSixOnSelector)
// executes, only if some options not declared here
default: return nil
}
}
private func buildFeature(identifier: Int, type: Int) -> FeatureType {
return [.featureIdentifier: identifier, .typeIdentifier: type]
}
}
// Usage:
let font = UIFont.systemFont(ofSize: 13, weight: .light).addFeatures([.lowerSmallCaps])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment