Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sketchytech/66b8ce202445087404e8 to your computer and use it in GitHub Desktop.
Save sketchytech/66b8ce202445087404e8 to your computer and use it in GitHub Desktop.
Functional NSAttributedString to NSAttributedString with added colour, highlight and underline
typealias Attributer = NSAttributedString -> NSAttributedString
func color(color:UIColor) -> Attributer {
return {(aString:NSAttributedString) in
let mString = aString.mutableCopy()
mString.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: aString.length))
return mString.copy() as! NSAttributedString
}
}
func underline(style:NSUnderlineStyle) -> Attributer {
return {aString in
let mString = aString.mutableCopy()
mString.addAttribute(NSUnderlineStyleAttributeName, value: style.rawValue, range: NSRange(location: 0, length: aString.length))
return mString.copy() as! NSAttributedString
}
}
func highlight(color:UIColor) -> Attributer {
return {(aString:NSAttributedString) in
let mString = aString.mutableCopy()
mString.addAttribute(NSBackgroundColorAttributeName, value: color, range: NSRange(location: 0, length: aString.length))
return mString.copy() as! NSAttributedString
}
}
let aString = NSAttributedString(string: "Hello Swift!")
let addUnderline = underline(NSUnderlineStyle.StyleSingle)
let addColor = color(UIColor.brownColor())
let addHighlight = highlight(UIColor.yellowColor())
addColor(aString)
addUnderline(aString)
addHighlight(aString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment