Skip to content

Instantly share code, notes, and snippets.

@rhenz
Last active June 25, 2022 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhenz/b7798f87d6a83739c0d129c5174591da to your computer and use it in GitHub Desktop.
Save rhenz/b7798f87d6a83739c0d129c5174591da to your computer and use it in GitHub Desktop.
Attributed String using ResultBuilder and some methods by extending NSMutableAttributedString
@resultBuilder
enum AttributedStringBuilder {
static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString {
let attributedString = NSMutableAttributedString()
for component in components {
attributedString.append(component)
}
return attributedString
}
}
extension NSMutableAttributedString {
public func color(_ color: UIColor) -> NSMutableAttributedString {
self.addAttribute(NSAttributedString.Key.foregroundColor,
value: color,
range: NSRange(location: 0, length: self.length)
)
return self
}
public func font(_ font: UIFont) -> NSMutableAttributedString {
self.addAttribute(NSAttributedString.Key.font,
value: font,
range: NSRange(location: 0, length: self.length)
)
return self
}
}
// @AttributedStringBuilder
// func greetBuilder(name: String, title: String) -> NSAttributedString {
// NSMutableAttributedString(string: "Hello ")
// NSMutableAttributedString(string: name)
// .color(.red)
// NSMutableAttributedString(string: ", ")
// NSMutableAttributedString(string: title)
// .font(.systemFont(ofSize: 20))
// .color(.blue)
// }
// greetBuilder(name: "Naruto Uzumaki", title: "The Seventh Hokage")
//: Using typealias
typealias Text = NSMutableAttributedString
@AttributedStringBuilder
func greetBuilder(name: String, title: String) -> NSAttributedString {
Text("Hello ")
Text(name)
.color(.red)
Text(", ")
Text(title)
.font(.systemFont(ofSize: 20))
.color(.blue)
}
extension NSMutableAttributedString {
convenience init(_ string: String) {
self.init(string: string)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment