在代码中创建NSAttributedString对象可能很繁琐。这个库添加了一个可以轻松将属性应用于字符串的辅助对象。
创建具有不同格式化处理的 NSAttributedString 对象涉及到大量代码。如果您有一些基本的格式化需求和一些字符串,这个库允许快速创建 NSAttributedString。
辅助类名为Attributed
,包含一组格式化属性,然后提供一组简单的方法将属性应用于字符串或NSAttributedString。它还提供了一种将字符串和NSAttributedString组合的方法。
Attributed
对象let noFormatting = Attributed()
let redText = Attributed(color: NSColor.redColor())
let blueText = Attributed(color: NSColor.blueColor())
let boldText = Attributed(font: NSFont.boldSystemFontOfSize(24))
let detailsText = Attributed(attributes: [NSForegroundColorAttributeName: NSColor.greenColor(), NSFontAttributeName: NSFont.systemFontOfSize(18)])
Attributed
对象let stringWithAttributes = redText.toString { "Hi mom!" }
let attributedStringWithAttributes = redText.toString { NSAttributedString(string: "The quick brown fox") }
let multipleStrings = boldText.combine(strings: "Hi mom!", "The quick brown fox")
let nestedStrings = redText.toString { boldText.toString { "Header: " } + "here are the details" }
let anotherNestedString = redText.toString { boldText.toString { "Header: " } + detailsText.toString { "here are the details" } + blueText.toString{ "@" } }
let addedString = stringWithAttributes + " How are you?"