Attributed

Build Status CodeCov Swift 5.0 CocoaPods compatible Carthage compatible License

用于 Attributed 字符串的微框架。

什么是 Attributed?

Attributed 旨在成为当前 NSAttributedString API 版本的即插即用替代品。

NSAttributedString 接口有一些缺点。如果您不知道设置特定属性所需的键和值类型,则必须花费时间查阅文档。另一个担忧是安全性:将 [String: Any] 类型的字典传递给 NSAttributedString 的构造函数可能会导致运行时崩溃。

Attributed 通过使用流畅、强类型且易于使用的 API 扩展当前的 NSAttributedString 接口,为开发者提供了一个更友好的替代方案。

特性

没有看到您需要的功能?

欢迎提出 issue 请求您想要的功能,或发送 pull request!

用法

通过闭包组合创建新的 NSAttributedString

"This is not a string".at.attributed {
  return $0.foreground(color: .red)
           .font(UIFont(name: "Chalkduster", size: 24.0)!)
           .underlineStyle(.styleSingle)
}

通过传递属性对象创建新的 NSAttributedString

首先创建一个 Attributes 对象

let attributes = Attributes {
    return $0.foreground(color: .red)
             .font(UIFont(name: "Chalkduster", size: 24.0)!)
             .underlineStyle(.styleSingle)
}

然后只需将 Attributes 应用于 String

"Hello".at.attributed(with: attributes)

使用 + 组合 NSAttributedString

这个库定义了一个连接运算符 +,用于连接 NSAttributedString 的实例。 +NSAttributedString 的作用与对 String 的作用相同。这对于组合具有不同属性的 NSAttributedStrings 以产生所需效果非常有用,而无需指定范围来应用不同的属性。

let bodyAttributes = Attributes { 
    return $0.foreground(color: .purple)
             .font(UIFont(name: "Noteworthy-Light", size: 20.0)!)
}

let authorAttributes = bodyAttributes.foreground(color: .black)

"I think theres something strangely musical about noise.".at.attributed(with: bodyAttributes)
+ "\n  - Trent Reznor".at.attributed(with: authorAttributes)

安装

Carthage

如果您使用 Carthage 管理您的依赖项,只需将 Attributed 添加到您的 Cartfile

github "Nirma/Attributed"

如果您使用 Carthage 构建依赖项,请确保已将 Attributed.framework 添加到目标的“Linked Frameworks and Libraries”部分,并将 Attributed.framework 包含在 Carthage framework copying 构建阶段。

CocoaPods

如果您使用 CocoaPods 管理您的依赖项,只需将 Attributed 添加到您的 Podfile

pod 'AttributedLib'

要求

贡献

非常欢迎贡献!

许可证

Attributed 是自由软件,可以根据 LICENSE 文件中规定的条款进行重新分发。