50 lines
1.7 KiB
Swift
50 lines
1.7 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)? {
|
|
guard let value = value as? AnyHashable else { return nil }
|
|
|
|
guard let font = value as? UIFont, let style = TypographicalStyle.style(for: font.fontName, size: font.pointSize), key == .font
|
|
else {
|
|
return AnyAttribute(location: range.location, length: range.length, key: key, value: value)
|
|
}
|
|
return FontLabelAttribute(location: range.location, length: range.length, style: style)
|
|
}
|
|
}
|