Last active
January 31, 2024 12:36
-
-
Save priyankt/4040871f8158c1ff33894ea959fe22ef to your computer and use it in GitHub Desktop.
Attributed text generation helper classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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