// // String+Attributed.swift // ToMove // // Created by Saveliy Stavitsky on 4/26/20. // Copyright © 2020 Saveliy Stavitsky. All rights reserved. // import UIKit // MARK: - REFACTOR typealias AttributedString = NSMutableAttributedString extension UIFont { enum Style: String { case regular = "Regular" case medium = "Medium" case bold = "Bold" } static func font(style: Style, size: CGFloat) -> UIFont { UIFont(name: "GolosUI-\(style.rawValue)", size: size)! } } extension String { var attributed: AttributedString { .init(string: self) } func attributed( style: UIFont.Style = .regular, size: CGFloat = 12, color: UIColor = Asset.textGranite.color, alignment: NSTextAlignment = .left ) -> AttributedString { let paragraph = NSMutableParagraphStyle() paragraph.alignment = alignment return .init(string: self, attributes: [ .font: UIFont.font(style: style, size: size), .foregroundColor: color, .paragraphStyle: paragraph ]) } func attributed(named: String, color: UIColor = Asset.textGranite.color) -> AttributedString { let comps = named.components(separatedBy: "_") guard comps.count == 2, (Int(comps[1]) ?? 0) > 6 else { return attributed } return attributed(style: ([ "regular": .regular, "medium": .medium, "bold": .bold ] as [String: UIFont.Style])[comps[0]] ?? .regular, size: CGFloat(Int(comps[1]) ?? 0), color: color) } } extension NSAttributedString { func applying(attribute: NSAttributedString.Key, value: Any) -> AttributedString { let copy = NSMutableAttributedString(attributedString: self) copy.addAttribute(attribute, value: value, range: (string as NSString).range(of: string)) return copy } static func + (lhs: NSAttributedString, rhs: NSAttributedString) -> AttributedString { let string: AttributedString = .init(attributedString: lhs) // .configure({ $0.append(lhs) }) string.append(rhs) return .init(attributedString: string) } static func + (lhs: NSAttributedString, rhs: String) -> AttributedString { let string = AttributedString(attributedString: lhs) string.append(rhs.attributed) return .init(attributedString: string) } }