Created
May 16, 2016 23:36
-
-
Save JoeFerrucci/4a574815022847e6045dd07b3d4c0d99 to your computer and use it in GitHub Desktop.
A functional wrapper around NSMutableAttributedString
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
/* | |
let myName = NSMutableAttributedString(string: " Hey, what's up!? ") | |
let yellowOnBlack = Styles.textBackground(.redColor(), range: NSMakeRange(2, 3)) >>> Styles.textColor(.darkGrayColor()) | |
let label = UILabel(frame: CGRectMake(10, 50, 200, 50)) | |
label.attributedText = yellowOnBlack(myName) | |
view.addSubview(label) | |
*/ | |
import UIKit | |
import Foundation | |
typealias TextStyle = NSMutableAttributedString -> NSMutableAttributedString | |
infix operator >>> { associativity left } | |
func >>> (style1: TextStyle, style2: TextStyle) -> TextStyle { | |
return { string in | |
style2(style1(string)) | |
} | |
} | |
class Styles { | |
static func textBackground(color: UIColor, range: NSRange? = nil) -> TextStyle { | |
return { mutableAttributedString in | |
let newString = NSMutableAttributedString(attributedString: mutableAttributedString) | |
if let r = range { | |
newString.addAttribute(NSBackgroundColorAttributeName, value: color, range: r) | |
} else { | |
let r = NSRange(location: 0, length: mutableAttributedString.string.characters.count) | |
newString.addAttribute(NSBackgroundColorAttributeName, value: color, range: r) | |
} | |
return newString | |
} | |
} | |
static func textColor(color: UIColor) -> TextStyle { | |
return { mutableAttributedString in | |
let newString = NSMutableAttributedString(attributedString: mutableAttributedString) | |
let range = NSRange(location: 0, length: mutableAttributedString.string.characters.count) | |
newString.addAttribute(NSForegroundColorAttributeName, value: color, range: range) | |
return newString | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment