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
// | |
// 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