Forked from dduan/NSAttributedString+SimpleHTMLTag.swift
Last active
August 29, 2015 14:17
-
-
Save cactis/31255b65dfb365bf4c16 to your computer and use it in GitHub Desktop.
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