From f842f99e82f72707a261590cd168e6afbd659555 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Sun, 15 Dec 2024 02:10:12 -0500 Subject: [PATCH] Add `UIFont` --- Sources/Silica/UIKit/UIFont.swift | 74 +++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Sources/Silica/UIKit/UIFont.swift diff --git a/Sources/Silica/UIKit/UIFont.swift b/Sources/Silica/UIKit/UIFont.swift new file mode 100644 index 0000000..1293c8d --- /dev/null +++ b/Sources/Silica/UIKit/UIFont.swift @@ -0,0 +1,74 @@ +// +// UIFont.swift +// Cacao +// +// Created by Alsey Coleman Miller on 5/31/16. +// Copyright © 2016 PureSwift. All rights reserved. +// + +import struct Foundation.CGFloat + +public final class UIFont { + + // MARK: - Properties + + public let cgFont: CGFont + + // MARK: Font Name Attributes + + public var fontName: String { return cgFont.name } + + public var familyName: String { return cgFont.family } + + // MARK: Font Metrics + + public let pointSize: CGFloat + + public lazy var descender: CGFloat = (CGFloat(self.cgFont.scaledFont.descent) * self.pointSize) / CGFloat(self.cgFont.scaledFont.unitsPerEm) + + public lazy var ascender: CGFloat = (CGFloat(self.cgFont.scaledFont.ascent) * self.pointSize) / CGFloat(self.cgFont.scaledFont.unitsPerEm) + + // MARK: - Initialization + + public init?(name: String, size: CGFloat) { + + guard let cgFont = CGFont(name: name) + else { return nil } + + self.cgFont = cgFont + self.pointSize = size + } +} + +// MARK: - Extensions + +public extension UIFont { + + static func systemFont(ofSize size: CGFloat) -> UIFont { + return UIFont(name: "HelveticaNeu", size: size)! + } + + static func boldSystemFont(ofSize size: CGFloat) -> UIFont { + return UIFont(name: "HelveticaNeu-Bold", size: size)! + } +} + +// MARK: - Equatable + +extension UIFont: Equatable { + + public static func == (lhs: UIFont, rhs: UIFont) -> Bool { + return lhs.fontName == rhs.fontName + && lhs.pointSize == rhs.pointSize + } +} + +// MARK: - Hashable + +extension UIFont: Hashable { + + public func hash(into hasher: inout Hasher) { + hasher.combine(fontName) + hasher.combine(pointSize) + } +}