XLAttributedString 1.3.0

XLAttributedString 1.3.0

swiftneko 维护。



  • 作者:
  • xiaolong.jin

XLAttributedString

使用 SwiftUI 风格语法来组合 NSAttributedString,由当前的 Function Builder 功能推动。

项目链接: https://github.com/swiftneko/AttributedStringBuilder

特性

特性
🐦 使用 Swift 5.1 编写的开源库
🍬 支持 SwiftUI 风格语法,支持 if-else / ForEach
💪 支持 NSAttributedString.Key 的大多数属性
📦 使用 Swift Package Manager 进行分发
🧪 完全测试过的代码

如何使用?

传统上,我们这样组合 NSAttributedString

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
    }()
]))
// ...

现在,有了 XLAttributedString,我们可以使用 SwiftUI 风格的语法来声明 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)" }
}

要求

Xcode 11。此项目使用 Swift 5.1 的 Function Builder 功能。

安装

Swift 包

在 Xcode 11 中打开您的项目,导航到 菜单 -> Swift 包 -> 添加包依赖 并输入 https://github.com/swiftneko/XLAttributedString 进行安装。

CocoaPods

在您的 Podfile 中添加 pod 'XLAttributedString'

示例应用

打开 XLAttributedString.xcworkspace 并运行 XLAttributedStringApp 目标。

code demo

其他

一些代码灵感来自 ethanhuang13🙏.