CocoaPods trunk is moving to be read-only. Read more on the blog, there are 18 months to go.

BKAttributedStringBuilder 1.2.0

BKAttributedStringBuilder 1.2.0

Maintained by swiftneko.



  • By
  • codeswifter

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.

code demo

Others

Some code are inspired by ethanhuang13๐Ÿ™.