Skip to content

Instantly share code, notes, and snippets.

@popcornomnom
Last active March 29, 2020 11:39
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 popcornomnom/8e890922dbc3ad63c8bbc05d6e3f9c4c to your computer and use it in GitHub Desktop.
Save popcornomnom/8e890922dbc3ad63c8bbc05d6e3f9c4c to your computer and use it in GitHub Desktop.
//
// FontManager.swift
//
// Created by http://www.popcornomnom.com
// Copyright © 2020 Marharyta Lytvynenko. All rights reserved.
//
import UIKit
///optional type in case if you don't want to support scaled font yet
private let autoScaleSettings: AutoScaleSettings? = AutoScaleSettings()
private class AutoScaleSettings {
let mostPopularScreenWidth: CGFloat = 375
let maxScreenWidth: CGFloat = 460 //use to prevent huge font scalinh on iPad
let minScaleFactor: CGFloat = 0.93 //to protect scalling of very small sizes
}
//MARK: - Font Parts
public extension UIFont {
enum Family: String, CaseIterable {
case system = ".SFUIText" //".SFUI"
case inter = "Inter"
//easy to change default app fonts family
public static let defaultFamily = Family.inter
}
enum CustomWeight: String, CaseIterable {
case regular = "", medium, light, heavy, bold, semibold, black
}
enum Size: CGFloat, CaseIterable {
case h1 = 36, h2 = 28, h3 = 20
case bodyL = 17, bodyM = 15, bodyS = 13
var doesSupportMinScalling: Bool { return rawValue > Size.bodyM.rawValue } //readability bounds
}
private class func stringName(_ family: Family, _ weight: CustomWeight) -> String {
/**
Define incompatible family, weight here
in this case set defaults compatible values
*/
let fontWeight: String
switch (family, weight) {
case (.inter, .heavy): fontWeight = CustomWeight.bold.rawValue
case (.inter, .light): fontWeight = "\(weight.rawValue)BETA"
default: fontWeight = weight.rawValue
}
//put Family and Weight together
let familyName = family.rawValue
return fontWeight.isEmpty ? "\(familyName)" : "\(familyName)-\(fontWeight)"
}
}
//MARK: - Initializers
public extension UIFont {
convenience init(_ size: Size, _ weight: CustomWeight) {
self.init(.defaultFamily, size, weight)
}
convenience init(_ family: Family = .defaultFamily,
_ size: Size, _ weight: CustomWeight) {
var _size = size.rawValue
if let autoScaleSettings = autoScaleSettings {
var ratio = (min(UIScreen.main.bounds.width,
autoScaleSettings.maxScreenWidth)
/ autoScaleSettings.mostPopularScreenWidth)
ratio = max(autoScaleSettings.minScaleFactor, ratio)
if ratio > 1 || (ratio < 1 && size.doesSupportMinScalling) {
_size = round(ratio * _size)
}
}
self.init(name: UIFont.stringName(family, weight), size: _size)!
}
}
// *DEBUG* https://gist.github.com/popcornomnom/a677d549aa216b071ac92d336557c63b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment