Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created November 30, 2015 17:59
Show Gist options
  • Select an option

  • Save ajjames/156f225e1b49e65b8834 to your computer and use it in GitHub Desktop.

Select an option

Save ajjames/156f225e1b49e65b8834 to your computer and use it in GitHub Desktop.
String Extension for Formatting AttributedStrings
extension String
{
func attributeString(font1:UIFont, font2:UIFont, color1:UIColor = UIColor.blackColor(), color2:UIColor = UIColor.blackColor()) -> NSAttributedString
{
let attributes1 = [NSFontAttributeName:font1, NSForegroundColorAttributeName:color1]
let attributes2 = [NSFontAttributeName:font2, NSForegroundColorAttributeName:color2]
return attributeString("|", attributes1:attributes1, attributes2:attributes2)
}
func attributeString(delimiter:Character, attributes1:[String:AnyObject], attributes2:[String:AnyObject]) -> NSAttributedString
{
let textArray = markedString.characters.split{$0 == delimiter}.map(String.init)
let mutableAttributedString = NSMutableAttributedString()
for index in 0..<textArray.count
{
let currentString = textArray[index]
var attributes = [String:AnyObject]()
if index % 2 == 0
{
attributes = attributes1
}
else
{
attributes = attributes2
}
let attributedString = NSAttributedString(string:currentString, attributes:attributes)
mutableAttributedString.appendAttributedString(attributedString)
}
return NSAttributedString(attributedString:mutableAttributedString)
}
}
var markedString = "Make |this text bold|. But not this text."
let outerFont = UIFont(name:"HelveticaNeue-Light", size:18)!
let innerFont = UIFont(name:"HelveticaNeue-Bold", size:20)!
markedString.attributeString(outerFont, font2:innerFont)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment