Created
December 7, 2014 05:59
-
-
Save dduan/6e60367fa03263da1c29 to your computer and use it in GitHub Desktop.
Convert Simple Text With HTML Tags to NSAttributedString
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
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