Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,35 @@ let attributedString = NSAttributedString {

```

Add Conditional String Builder and Loop String Builder

```Swift
@NSAttributedStringBuilder
var attributedString:NSAttributedString{
AText("Hello world")
.attribute(.foregroundColor, value: Color.blue)

for character in ["a", "b", "c", "d"] {
AText(character)
.backgroundColor(UIColor.red)
.alignment(.left)
}

if condition {
AText("True")
.foregroundColor(UIColor.black)
}
else{
AText("False")
.backgroundColor(UIColor.yellow)
}
}
```



## Requirements

Xcode 12.5. This project uses Swift 5.4 feature [Result Builder](https://github.com/apple/swift-evolution/blob/main/proposals/0289-result-builders.md).

## Installation
Expand Down
32 changes: 32 additions & 0 deletions Sources/NSAttributedStringBuilder/NSAttributedStringBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,49 @@ public typealias Attributes = [NSAttributedString.Key: Any]

@resultBuilder
public enum NSAttributedStringBuilder {
public static func buildOptional(_ component: NSAttributedString?) -> Component {

if let content = component {
return AText(content.string, attributes: content.attributesAll)
}
else{
return AText("")
}
}

public static func buildBlock(_ components: Component...) -> NSAttributedString {
let mas = NSMutableAttributedString(string: "")
for component in components {
mas.append(component.attributedString)
}
return mas
}

public static func buildEither(first component: NSAttributedString) -> Component {
return AText(component.string, attributes: component.attributesAll)
}

public static func buildEither(second component: NSAttributedString) -> Component {
return AText(component.string, attributes: component.attributesAll)
}

public static func buildArray(_ components: [NSAttributedString]) -> Component {
let mas = NSMutableAttributedString(string: "")
for component in components {
mas.append(component)
}
return AText(mas.string, attributes: mas.attributes(at: 0, effectiveRange: nil))
}

}

public extension NSAttributedString {
convenience init(@NSAttributedStringBuilder _ builder: () -> NSAttributedString) {
self.init(attributedString: builder())
}

var attributesAll:[NSAttributedString.Key : Any] {
self.attributes(at: 0, effectiveRange: nil)
}

}