Skip to content

Instantly share code, notes, and snippets.

@dduan
Created December 7, 2014 05:59
Show Gist options
  • Save dduan/6e60367fa03263da1c29 to your computer and use it in GitHub Desktop.
Save dduan/6e60367fa03263da1c29 to your computer and use it in GitHub Desktop.
Convert Simple Text With HTML Tags to NSAttributedString
extension NSAttributedString {
func replaceHTMLTag(tag: String, withAttributes attributes: [String: AnyObject]) -> NSAttributedString {
let openTag = "<\(tag)>"
let closeTag = "</\(tag)>"
let resultingText: NSMutableAttributedString = self.mutableCopy() as NSMutableAttributedString
while true {
let plainString = resultingText.string as NSString
let openTagRange = plainString.rangeOfString(openTag)
if openTagRange.length == 0 {
break
}
let affectedLocation = openTagRange.location + openTagRange.length
var searchRange = NSMakeRange(affectedLocation, plainString.length - affectedLocation)
let closeTagRange = plainString.rangeOfString(closeTag, options: NSStringCompareOptions(0), range: searchRange)
resultingText.setAttributes(attributes, range: NSMakeRange(affectedLocation, closeTagRange.location - affectedLocation))
resultingText.deleteCharactersInRange(closeTagRange)
resultingText.deleteCharactersInRange(openTagRange)
}
return resultingText as NSAttributedString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment