BKAttributedStringBuilder
Composing NSAttributedString
with SwiftUI-style syntax, powered by the now pitching Function Builder.
Project Link: https://github.com/codeswifter/BKAttributedStringBuilder
Features
Features | |
---|---|
Open source library written in Swift 5.0 | |
SwiftUI-like syntax, supports if-else / ForEach | |
Support most attributes in NSAttributedString.Key |
|
Distribution with Swift Package Manager | |
Fully tested code |
How to use?
Traditionally we compose a NSAttributedString
like this:
let mas = NSMutableAttributedString(string: "")
mas.append(NSAttributedString(string: "Hello", attributes: [
.foregroundColor: UIColor.red,
.backgroundColor: UIColor.yellow,
.font: UIFont.systemFont(ofSize: 20)
]))
mas.append(NSAttributedString(string: "\n"))
mas.append(NSAttributedString(string: "World", attributes: [
.font: UIFont.systemFont(ofSize: 40),
.paragraphStyle: {
let p = NSMutableParagraphStyle()
p.firstLineHeadIndent = 20
return p
}()
]))
// ...
Now, with BKAttributedStringBuilder, we can use SwiftUI-like syntax to declare NSAttributedString
:
let usingEnglish = false
label.attributedText = NSAttributedString {
"Hello".foregroundColor(.red)
.backgroundColor(.yellow)
.font(.systemFont(ofSize: 20))
"\n"
if usingEnglish {
"World".font(.systemFont(ofSize: 40))
.backgroundColor(.red)
.paragraphStyle {
let p = NSMutableParagraphStyle()
p.firstLineHeadIndent = 20
return p
}
} else {
"ใใใ".font(.systemFont(ofSize: 40))
.backgroundColor(.red)
}
"\n"
ForEach(1 ..< 5) {
"\($0)"
WhiteSpace(count: $0)
}
}
Requirements
Xcode 14. This project uses Swift 5.1 feature Function Builder.
Installation
Swift Package
Open your project in Xcode 14, navigate to Menu -> Swift Packages -> Add Package Dependency and enter https://github.com/codeswifter/BKAttributedStringBuilder to install.
Demo App
Open BKAttributedStringBuilder.xcworkspace and run BKAttributedStringBuilderDemo_iOS
target.
Others
Some code are inspired by ethanhuang13