vds_ios/VDS/Components/Label/Attributes/LabelAttributeModel.swift
2022-11-10 09:44:38 -05:00

54 lines
1.8 KiB
Swift

//
// LabelAttributeModel.swift
// VDS
//
// Created by Matt Bruce on 8/3/22.
//
import Foundation
import UIKit
public protocol LabelAttributeModel: AnyEquatable, Withable, Equatable, Identifiable where ID == UUID {
var location: Int { get set }
var length: Int { get set }
func setAttribute(on attributedString: NSMutableAttributedString)
}
extension LabelAttributeModel {
public var range: NSRange {
NSRange(location: location, length: length)
}
public static func == (lhs: any LabelAttributeModel, rhs: any LabelAttributeModel) -> Bool {
lhs.isEqual(rhs)
}
}
public extension NSAttributedString {
func createAttributeModels() -> [(any LabelAttributeModel)] {
var attributes: [any VDS.LabelAttributeModel] = []
enumerateAttributes(in: NSMakeRange(0, length)) { attributeMap, range, stop in
attributeMap.forEach { (key: NSAttributedString.Key, value: Any) in
if let attribute = NSAttributedString.createAttributeModelFor(key: key, range: range, value: value) {
attributes.append(attribute)
}
}
}
return attributes
}
static func createAttributeModelFor(key: NSAttributedString.Key, range: NSRange, value: Any) -> (any LabelAttributeModel)? {
switch key {
case NSAttributedString.Key.font:
let value = value as! UIFont
let style = TypographicalStyle.style(for: value.fontName, size: value.pointSize)
return FontLabelAttribute(location: range.location, length: range.length, style: style)
case NSAttributedString.Key.foregroundColor:
return ColorLabelAttribute(location: range.location, length: range.length, color: value as! UIColor)
default:
return nil
}
}
}