Skip to content

Instantly share code, notes, and snippets.

@priyankt
Last active January 31, 2024 12:36
Show Gist options
  • Save priyankt/4040871f8158c1ff33894ea959fe22ef to your computer and use it in GitHub Desktop.
Save priyankt/4040871f8158c1ff33894ea959fe22ef to your computer and use it in GitHub Desktop.
Attributed text generation helper classes
import Foundation
import UIKit
class AttributedTextComponent {
let text: String
let font: UIFont
let color: UIColor
init(text: String, font: UIFont, color: UIColor) {
self.text = text
self.font = font
self.color = color
}
}
class AttributedText {
var components = [AttributedTextComponent]()
var separator = ""
convenience init(components: [AttributedTextComponent], separator: String) {
self.init()
self.components = components
self.separator = separator
}
func plainString() -> String {
return components.map{ $0.text }.joined(separator: separator)
}
func attributedString() -> NSAttributedString? {
let plainString = self.plainString()
let attrStr = NSMutableAttributedString(
string: plainString
)
for component in components {
attrStr.addAttributes(
[
NSAttributedStringKey.foregroundColor: component.color,
NSAttributedStringKey.font: component.font
],
range: (plainString as NSString).range(of: component.text)
)
}
return attrStr
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment