PrettyString
PrettyString定义了一种高度可自定义、极其简单的语法,用于使字符串更美观。
当有基于XML、HTML和Markdown的替代品时,PrettyString比Markdown提供了更大的灵活性,其语法比HTML更清洁。
使用方法
PrettyString允许你指定字符串中的部分以使用某些属性进行样式化。为了表示一个部分,使用语法{name:text}
,如下所示
let string = "Hello this is some {blue:blue text}"
在这里,名称是blue
,文本是blue text
。然而,这个名称的含义完全取决于你自己。没有内置的样式。幸运的是,定义样式非常简单
let config = PrettyString.Config(
base: [],
rules: [
PrettyString.Config.Rule(
name: "blue",
attributes: [
.foregroundColor(UIColor.blue)
]
)
]
)
它看起来有点大,但它真的很简单。配置由两部分组成:一个是base
,另一个是一些rules
。
基础是一个包含应用于整个字符串的Attribute
的列表。
然后是rules
的列表。每个规则都有一个名称,例如blue
,并在遇到此名称时适用一系列Attribute
。
一旦你有一个字符串和一个Config
,你就可以美化你的字符串了!
let attributedString = try! string.prettify(config)
请注意,从String
到NSAttributedString
的转换可能失败,因此你必须使用try
或它的变体来处理错误。抛出的错误类型为PrettyString.Error
,可能会提供一些关于你的字符串为何无法解析的提示。
如果你总是使用相同的Config
对象,你甚至可以设置默认的配置,这样调用不带参数的prettify
将自动使用它。这意味着下面的attributedString
与上面的相同!
PrettyString.Config.default = config
let attributedString = try! string.prettify()
属性
所有属性的完整列表如下
enum Attribute {
case attachment(NSTextAttachment)
case backgroundColor(UIColor)
case baselineOffset(Float)
case expansion(Float)
case font(UIFont)
case foregroundColor(UIColor)
case kern(Float)
case ligature(Int)
case link(URL)
case obliqueness(Float)
case paragraphStyle(NSParagraphStyle)
case shadow(NSShadow)
case strikethroughColor(UIColor)
case strikethroughStyle(Int)
case strokeColor(UIColor)
case strokeWidth(Float)
case textEffect(String)
case underlineColor(UIColor)
case underlineStyle(NSUnderlineStyle)
case writingDirection([Int])
}
每个属性都对应同名的 NSAttributedStringKey
。它们的使用应该相对直观。
高级用法
转义字符
所有常规转义字符和 Unicode 序列都应该 正常工作,但是如何在你的字符串中实际写入 {
或 }
字符呢?要这样做,请在其前面使用额外的 {
进行转义。
也就是说,这样: "{{他说:hello{"
确实会给你字符串 {他说:hello}
而不是尝试找到一个名为 他说
的规则并应用于 hello{
。
嵌套
属性段的嵌套也可以正常工作。最内部段的属性将覆盖外部的任何样式,类似于命名部分将覆盖基本样式
{绿色斜体:hello {红色加粗:there}}
应该显示为绿色斜体的 "hello" 和红色加粗的斜体 "there"(假设你很好地命名了规则)。
规则名称
实际规则可以包含任何字符 除了 :
,因为它用于标记名称的结束。你甚至可以在名称中使用 {
或 }
,只要它们不是第一个字符。但我真的不建议这样做,最好坚持使用常规字母、下划线和连字符,因为这样最终会更加清晰。
显式API
如果不喜欢使用对 String
类型的扩展,可以直接使用 PrettyString
结构体。
let string = "This is some {blue:blue text}"
let prettyString = PrettyString(string, config: config)
let attributedString = try! prettyString.parse()
要求
本项目使用 Swift 4,您也应使用 Swift 4。
安装
PrettyString 通过 CocoaPods 提供。要安装,只需将以下行添加到 Podfile
pod 'PrettyString', '~> 0.1'
作者
Cameron Eldridge, [email protected]
许可证
PrettyString 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。