Skip to content

Instantly share code, notes, and snippets.

View carson-katri's full-sized avatar

Carson Katri carson-katri

View GitHub Profile
@_functionBuilder
struct AttributedStringBuilder {
...
static func buildIf(_ segment: NSAttributedString?) -> NSAttributedString {
segment ?? NSAttributedString()
}
}
HStack {
if greeting != nil {
Text("\(greeting!) ")
}
Text("World")
}
NSAttributedString {
"Hello "
.foregroundColor(.red)
.font(UIFont.systemFont(ofSize: 10.0))
"World"
.foregroundColor(.green)
.underline(.orange, style: .thick)
}
extension String {
func foregroundColor(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.foregroundColor : color])
}
func background(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.backgroundColor: color])
}
func underline(_ color: UIColor, style: NSUnderlineStyle = .single) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.underlineColor: color, .underlineStyle: style.rawValue])
}
extension String {
func colored(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.foregroundColor : color])
}
func background(_ color: UIColor) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.backgroundColor: color])
}
func underline(_ color: UIColor, style: NSUnderlineStyle = .single) -> NSAttributedString {
NSAttributedString(string: self, attributes: [.underlineColor: color, .underlineStyle: style.rawValue])
}
extension NSAttributedString {
convenience init(@AttributedStringBuilder _ content: () -> NSAttributedString) {
self.init(attributedString: content())
}
}
@_functionBuilder
struct AttributedStringBuilder {
static func buildBlock(_ segments: NSAttributedString...) -> NSAttributedString {
let string = NSMutableAttributedString()
segments.forEach { string.append($0) }
return string
}
}
NSAttributedString {
"Hello "
.color(.red)
"World"
.color(.blue)
.underline(.blue)
}
@_functionBuilder
struct GreetingBuilder {
static func buildBlock(_ items: String...) -> [String] {
return items.map { "Hello \($0)" }
}
}
func combineWords() -> TupleView<(Text, Text)> {
let _a = Text("Hello")
let _b = Text("World")
return ViewBuilder.buildBlock(_a, _b)
}