Last active
June 25, 2022 15:10
-
-
Save rhenz/b7798f87d6a83739c0d129c5174591da to your computer and use it in GitHub Desktop.
Attributed String using ResultBuilder and some methods by extending NSMutableAttributedString
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
@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