87 lines
2.6 KiB
Swift
87 lines
2.6 KiB
Swift
//
|
|
// LabelAttributeAction.swift
|
|
// VDS
|
|
//
|
|
// Created by Matt Bruce on 8/3/22.
|
|
//
|
|
|
|
import Foundation
|
|
import UIKit
|
|
import Combine
|
|
|
|
public protocol ActionLabelAttributeModel: LabelAttributeModel {
|
|
var accessibleText: String? { get set }
|
|
var action: PassthroughSubject<Void, Never> { get }
|
|
}
|
|
|
|
extension ActionLabelAttributeModel {
|
|
public func addHandler(on attributedString: NSMutableAttributedString){
|
|
attributedString.addAttribute(NSAttributedString.Key.action, value: "handler", range: range)
|
|
}
|
|
}
|
|
|
|
public struct ActionLabelAttribute: ActionLabelAttributeModel {
|
|
|
|
public static func == (lhs: ActionLabelAttribute, rhs: ActionLabelAttribute) -> Bool {
|
|
lhs.isEqual(rhs)
|
|
}
|
|
|
|
public func isEqual(_ equatable: ActionLabelAttribute) -> Bool {
|
|
return id == equatable.id && range == equatable.range
|
|
}
|
|
|
|
//--------------------------------------------------
|
|
// MARK: - Properties
|
|
//--------------------------------------------------
|
|
public var id = UUID()
|
|
public var location: Int
|
|
public var length: Int
|
|
public var shouldUnderline: Bool
|
|
public var accessibleText: String?
|
|
public var action = PassthroughSubject<Void, Never>()
|
|
public var subscriber: AnyCancellable?
|
|
//--------------------------------------------------
|
|
// MARK: - Initializer
|
|
//--------------------------------------------------
|
|
|
|
public init(location: Int, length: Int, shouldUnderline: Bool = true, accessibleText: String? = nil) {
|
|
self.location = location
|
|
self.length = length
|
|
self.shouldUnderline = shouldUnderline
|
|
self.accessibleText = accessibleText
|
|
}
|
|
|
|
private enum CodingKeys: String, CodingKey {
|
|
case location, length
|
|
}
|
|
|
|
public func setAttribute(on attributedString: NSMutableAttributedString) {
|
|
guard isValidRange(on: attributedString) else { return }
|
|
|
|
if(shouldUnderline){
|
|
UnderlineLabelAttribute(location: location, length: length).setAttribute(on: attributedString)
|
|
}
|
|
addHandler(on: attributedString)
|
|
}
|
|
}
|
|
|
|
extension NSAttributedString.Key {
|
|
public static let action = NSAttributedString.Key(rawValue: "action")
|
|
}
|
|
|
|
extension String {
|
|
public func nsRange(of text: String) -> NSRange? {
|
|
guard let found = range(of: text) else { return nil }
|
|
return NSRange(found, in: self)
|
|
}
|
|
}
|
|
|
|
|
|
extension ActionLabelAttribute {
|
|
|
|
public init? (text: String, linkText: String, accessibleText: String? = nil) {
|
|
guard let range = text.nsRange(of: linkText) else { return nil }
|
|
self.init(location: range.location, length: range.length)
|
|
}
|
|
}
|