Last active
August 29, 2015 14:23
-
-
Save sketchytech/66b8ce202445087404e8 to your computer and use it in GitHub Desktop.
Functional NSAttributedString to NSAttributedString with added colour, highlight and underline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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