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

XLAttributedString 1.3.0

XLAttributedString 1.3.0

Maintained by swiftneko.



  • By
  • xiaolong.jin

XLAttributedString

Composing NSAttributedString with SwiftUI-style syntax, powered by the now pitching Function Builder.

Project Link: https://github.com/swiftneko/AttributedStringBuilder

Features

Features
๐Ÿฆ Open source library written in Swift 5.1
๐Ÿฌ 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 XLAttributedString, we can use SwiftUI-like syntax to declare NSAttributedString:

let greeing = false
label.attributedText = NSAttributedString {
    "Hello".foregroundColor(.red)
        .backgroundColor(.yellow)
        .font(.systemFont(ofSize: 20))
    "\n"
    if greeting {
        "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)" }
}

Requirements

Xcode 11. This project uses Swift 5.1 feature Function Builder.

Installation

Swift Package

Open your project in Xcode 11, navigate to Menu -> Swift Packages -> Add Package Dependency and enter https://github.com/swiftneko/XLAttributedString to install.

CocoaPods

Add pod 'XLAttributedString' to your Podfile.

Demo App

Open XLAttributedString.xcworkspace and run XLAttributedStringApp target.

code demo

Others

Some code are inspired by ethanhuang13๐Ÿ™.