是 NSAttributedString 的功能包装,用于轻松字符串样式化
使用 NSAttributedString 样式化字符串需要大量的痛苦和难看的代码,例如改变子字符串的颜色并加下划线需要
let string = NSMutableAttributedString(string: "Hello")
string.addAttribute(NSforegroundAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, 5))
string.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSMakeRange(0, string.length))
ouch!
这很快就会变成一大块代码,难以阅读和维护。使用 stylize 后,我们的代码如下所示
let string = NSAttributedString(string: "Hello World")
let foregroundStyle = Stylize.foreground(UIColor.redColor(), range: NSMakeRange(0, 5))
let underlineStyle = Stylize.underline(NSUnderlineStyle.StyleSingle)
let style = Stylize.compose(foregroundStyle, underlineStyle)
let styledString = style(string)
这样就好了。
git submodule add https://github.com/alexfish/stylize.git
将 Stylize 添加到您的项目作为子模块Stylize.xcodeproj
拖到您的项目树中Stylize.framework
添加到您的目标 Link Binary with Libraries
构建阶段import Stylize
添加 Stylize 并准备开始使用let string = NSAttributedString(string: "Hello World")
let style = Stylize.foreground(UIColor.redColor())
let styledString = style(string)
默认情况下,样式将应用于整个字符串;如果您需要将样式应用于子字符串,每个样式都提供了可选的 range
参数
let string = NSAttributedString(string: "Hello World")
let style = Stylize.foreground(UIColor.redColor(), range: NSMakeRange(0, 5))
let styledString = style(string)
stylize 有一个 compose
函数,可以组合多个样式
let string = NSAttributedString(string: "Hello World")
let foregroundStyle = Stylize.foreground(UIColor.redColor())
let backgroundStyle = Stylize.background(UIColor.orangeColor())
let underlineStyle = Stylize.underline(NSUnderlineStyle.StyleSingle)
let style = Stylize.compose(foregroundStyle, backgroundStyle, underlineStyle)
let styledString = style(string)
属性 | 函数 |
---|---|
NSUnderlineStyleAttributeName | underline(style: NSUnderlineStyle) |
NSUnderlineColorAttributeName | underline(color: UIColor) |
NSForegroundColorAttributeName | foreground(color: UIColor) |
NSBackgroundColorAttributeName | background(color: UIColor |
NSStrikethroughStyleAttributeName | strikethrough(style: NSUnderlineStyle) |
NSStrikethroughColorAttributeName | strikethrough(color: UIColor) |
NSLinkAttributeName | link(url: NSURL) |
NSParagraphStyleAttributeName | paragraph(style: NSParagraphStyle) |
NSKernAttributeName | kern(points: NSNumber) |
NSBaselineOffsetAttributeName | baseline(offset: NSNumber) |
NSShadowAttributeName | shadow(shadow: NSShadow) |
NSStrokeWidthAttributeName | stroke(width: NSNumber) |
NSStrokeColorAttributeName | stroke(color: UIColor) |
NSTextEffectAttributeName | letterpress() |
NSFontAttributeName | font(font: UIFont) |
NSLigatureAttributeName | ligatures(enabled: Bool) |
NSObliquenessAttributeName | obliqueness(skew: NSNumber) |
NSAttachmentAttributeName | attachment(attachement: NSTextAttachment) |
NSExpansionAttributeName | expand(log: NSNumber) |
NSWritingDirectionAttributeName | direction(direction: WritingDirection) |