Skip to content

Instantly share code, notes, and snippets.

@omaarr90
Last active April 17, 2021 03:52
Show Gist options
  • Save omaarr90/b5ce4e5be41dd7cfce63078c594c9869 to your computer and use it in GitHub Desktop.
Save omaarr90/b5ce4e5be41dd7cfce63078c594c9869 to your computer and use it in GitHub Desktop.
I think I will finally be friend with NSAttributedString. This snippet uses _functionBuilder because I'm still running Xcode 12.4
import UIKit
typealias StyleAttributes = [NSAttributedString.Key: Any]
enum AttributedText {
case text(String, StyleAttributes)
case image(UIImage, StyleAttributes)
}
@_functionBuilder
struct AtributedSringBuilder {
static func buildBlock(_ texts: AttributedText...) -> [AttributedText] {
texts
}
}
func makeAttribtedString(@AtributedSringBuilder _ content: () -> [AttributedText]) -> NSAttributedString {
let result = NSMutableAttributedString()
for attributedText in content() {
switch attributedText {
case .text(let text, let attributes):
result.append(NSAttributedString(string: text, attributes: attributes))
case .image(let image, let attributes):
let attachment = NSTextAttachment(image: image)
let attr = NSMutableAttributedString(attachment: attachment)
attr.addAttributes(attributes, range: NSMakeRange(0, attr.string.count))
result.append(attr)
}
}
return result
}
let image = UIImage(systemName: "lock.fill")!
let attr = makeAttribtedString {
AttributedText.image(image, [.foregroundColor: UIColor.systemRed])
AttributedText.text("Hello, World!", [.foregroundColor: UIColor.systemTeal])
}
print(attr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment