Last active
January 12, 2018 18:43
-
-
Save algal/ddec8cf87e63e3cdbde6 to your computer and use it in GitHub Desktop.
Type-safe font initiazer
This file contains hidden or 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
// | |
// MARK: Font utilities | |
// | |
enum FontFamily : String { | |
case HelveticaNeue = "Helvetica Neue" | |
case MontSerrat = "Montserrat" | |
} | |
enum FontWeight { | |
case UltraLight,Thin,Light,Regular,Medium,Semibold,Bold,Heavy,Black | |
var asFontWeightTraitValue:CGFloat { | |
switch self { | |
case .UltraLight: return UIFontWeightUltraLight | |
case .Thin: return UIFontWeightThin | |
case .Light: return UIFontWeightLight | |
case .Regular: return UIFontWeightRegular | |
case .Medium: return UIFontWeightMedium | |
case .Semibold: return UIFontWeightSemibold | |
case .Bold: return UIFontWeightBold | |
case .Heavy: return UIFontWeightHeavy | |
case .Black: return UIFontWeightBlack | |
} | |
} | |
} | |
func getFont(family:FontFamily,weight:FontWeight,size:CGFloat) -> UIFont? { | |
let descriptor = UIFontDescriptor(fontAttributes:[ | |
UIFontDescriptorFamilyAttribute:family.rawValue, | |
UIFontWeightTrait:weight.asFontWeightTraitValue | |
]) | |
return UIFont(descriptor: descriptor, size: size) | |
} | |
extension UIFont { | |
convenience init(family:FontFamily,weight:FontWeight,size:CGFloat) | |
{ | |
let descriptor = UIFontDescriptor(fontAttributes:[ | |
UIFontDescriptorFamilyAttribute:family.rawValue, | |
UIFontWeightTrait:weight.asFontWeightTraitValue | |
]) | |
self.init(descriptor: descriptor, size: size) | |
} | |
} | |
// helpers | |
extension UIFont { | |
func scaled(scaleFactor:CGFloat) -> UIFont | |
{ | |
let descriptor:UIFontDescriptor = self.fontDescriptor() | |
let pointSize = descriptor.pointSize * scaleFactor | |
let newFont = UIFont(descriptor:descriptor,size:pointSize) | |
return newFont | |
} | |
func italicized() -> UIFont { | |
let descriptor:UIFontDescriptor = self.fontDescriptor() | |
let italicSymbolicTraits:UIFontDescriptorSymbolicTraits = .TraitItalic | |
if let newDescriptor = descriptor.fontDescriptorWithSymbolicTraits(italicSymbolicTraits) { | |
return UIFont(descriptor:newDescriptor,size:self.pointSize) | |
} | |
else { | |
return self | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment