Composing NSAttributedString with SwiftUI-style syntax, powerd by the now pitching Function Builder.
Project Link: https://github.com/ethanhuang13/NSAttributedStringBuilder
| Features | |
|---|---|
| 🐦 | Open source library written in Swift 5 |
| 🍬 | SwiftUI-like syntax |
| 💪 | Support most attributes in NSAttributedString.Key |
| 📦 | Distribution with Swift Package Manager |
| 🧪 | Fully tested code |
Traditionally we compose a NSAttributedString like this:
let mas = NSMutableAttributedString(string: "")
mas.append(NSAttributedString(string: "Hello world", attributes: [.font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.red]))
mas.append(NSAttributedString(string: "\n"))
mas.append(NSAttributedString(string: "with Swift", attributes: [.font: UIFont.systemFont(ofSize: 20), .foregroundColor: UIColor.orange]))Now, with NSAttributedStringBuilder, we can use SwiftUI-like syntax to declare NSAttributedString:
let attributedString = NSAttributedString {
AText("Hello world")
.font(.systemFont(ofSize: 24))
.color(.red)
LineBreak()
AText("with Swift")
.font(.systemFont(ofSize: 20))
.color(.orange)
}iOS 13, macOS 10.15, tvOS 13, or watchOS 13, because it uses Swift 5.1 features like Function Builder.
Please use Swift Package Manager to install.
Open your project in Xcode 11, navigate to Menu -> Swift Packages -> Add Package Dependency and enter https://github.com/ethanhuang13/NSAttributedStringBuilder to install.
Besides clearer NSAttributedString syntax, since NSAttributedStringBuilder uses Function Builder it also enables API to build components in UIViewRepresentable(which embbed UIView in a SwiftUI View).
Just like a SwiftUI Text takes a String as input, the purpose of AttributedText in the sample project is to take a NSAttributedString as input and render in SwiftUI.
To achieve this, AttributedText.swift uses @NSAttributedStringBuilder to support SwiftUI-style syntax:
Then using an AttributedText will be like:

Open the sample in /SwiftUISampleApp/AttributedTextSample.xcodeproj and check AttributedText. It uses UITextView, you can also use UILabel or NSTextView.
- Better tests for image attachment
NSAttributedStringdoes not support link color, thereforeLinkcomponent with a.color()modifier has no effect. Alternatively you need to specify inUITextView.linkTextAttributesor.tintColor.
Initially discussed on this Twitter thread. Some code are inspired by zonble🙏.
