// // NSAttributedString.swift // VDS // // Created by Matt Bruce on 5/30/23. // import Foundation import UIKit extension NSAttributedString { /// Spacer in the form of a AttributedString. /// - Parameter width: size of the space. /// - Returns: AttributedString with the Space of the width you asked. public static func spacer(for width: CGFloat) -> NSAttributedString { let spacerImage = UIImage() let spacerAttachment = NSTextAttachment() spacerAttachment.bounds = .init(x: 0, y: 0, width: width, height: 1) spacerAttachment.image = spacerImage return NSAttributedString(attachment: spacerAttachment) } } extension NSMutableAttributedString { /// This will used along with mutableText method to determine if you will use a ratio version of the lineHeight within a TextStyle if you have a scaled font being used. public static var useScaledLineHeight: Bool = false /// Creates a MutableAttributedString for the text and other properties you have passed into the method. /// - Parameters: /// - text: Text you want to draw onscreen. /// - textStyle: Style of Typography you want to render the Text. /// - useScaledFont: Determines if you used a scaledFont or a normal Font from the TextStyle. /// - textColor: Color of Text to render. /// - alignment: Text alignment. /// - lineBreakMode: LineBreak Mode. /// - Returns: MutableAttributedString from al lof the properties you passed in to help render Text using non-standard properties. public static func mutableText(for text: String, textStyle: TextStyle, useScaledFont: Bool = true, textColor: UIColor, alignment: NSTextAlignment = .left, lineBreakMode: NSLineBreakMode) -> NSMutableAttributedString { //var for if you can scale or not let scaledMode = useScaledFont && TextStyle.canScaleFonts //create the paragraph for specific properties let paragraph = NSMutableParagraphStyle() paragraph.alignment = alignment paragraph.lineBreakMode = lineBreakMode var defaultFont = textStyle.font var lineHeight = textStyle.lineHeight if scaledMode { defaultFont = defaultFont.scaledFont if useScaledLineHeight { lineHeight = textStyle.scaledLineHeight } } //set lineHeight if textStyle.lineHeight > 0.0 { paragraph.minimumLineHeight = lineHeight paragraph.maximumLineHeight = lineHeight } //create the attributeArray var attributes: [NSAttributedString.Key : Any] = [.font: defaultFont, .foregroundColor: textColor, .paragraphStyle: paragraph] //set letterSpacing attributes[.kern] = textStyle.letterSpacing return NSMutableAttributedString(string: text, attributes: attributes) } }