Created
August 22, 2016 06:41
-
-
Save unnamedd/941f89a8e4487dd5e91ce3834b38c89a to your computer and use it in GitHub Desktop.
NSTextAttachment
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
// MARK: - String Extension | |
private extension String { | |
/** | |
replace characters from the original text to some image | |
- parameter character: the character that will be used to be replaced by image | |
- parameter image: image name that will replace the character | |
*/ | |
func replace(char character: String, image: String) -> NSAttributedString { | |
// search for every check in front of the options | |
let regex = try! NSRegularExpression(pattern: character, options: [.IgnoreMetacharacters]) | |
let items = regex.matchesInString(self, options: [], range: NSRange(location: 0, length: self.characters.count)) | |
let ranges: [NSRange] = items.map { $0.range } | |
// replace every check character to new image | |
let attributedString = NSMutableAttributedString(string: self) | |
for range in ranges.reverse() { | |
let attachment = NSTextAttachment() | |
attachment.image = UIImage(named: image) | |
let attributedWithImage = NSAttributedString(attachment: attachment) | |
attributedString.replaceCharactersInRange(range, withAttributedString: attributedWithImage) | |
} | |
return attributedString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment