Attributed strings are a fantastic way to work with styled text on iOS and OS X. NSAttributedString is an incredibly full-featured API, but because of this, simple tasks sometimes require a fair amount of boilerplate code. Today we'll look at BonMot, a library from Raizlabs that simplifies the process of composing attributed strings.
BonMot takes the form of a set of chainable functions that we can use to compose attributed strings:
let fancyQuote = "Traveling through hyperspace ain't" +
"like dusting crops, farm boy.\n" +
" β Han Solo"
quoteLabel.attributedText = BONChain()
.fontNameAndSize("AmericanTypewriter", 17.0)
.lineHeightMultiple(1.8)
.string(fancyQuote)
.attributedString
BonMot will do all the heavy lifting of applying attributes and return a fully-formed NSAttributedString ready for use wherever we need.
We can use BonMot to concatenate multiple composed attributed strings:
let chain = BONChain()
chain.appendLink(BONChain().string("one fish"))
chain.appendLink(BONChain().string("two fish"), separator:commaSpace)
chain.appendLink(BONChain().string("red fish").textColor(UIColor.redColor()), separator:commaSpace)
chain.appendLink(BONChain().string("blue fish").textColor(UIColor.blueColor()), separator:commaSpace)
BonMot even supports the NSTextAttachment parts of the NSAttributedString API. We can generate an βimage next to a labelβ like this:
chain.appendLink(BONChain().image(ackbar))
chain.appendLink(
BONChain()
.fontNameAndSize("Futura-MediumItalic", 17.0)
.string("It's a trap!"), separator:" ")
We've only scratched the surface here, BonMot has a ton of features to offer. More info about BonMot can be found at git.io/bonmot