Skip to content

Instantly share code, notes, and snippets.

@unnamedd
Created August 22, 2016 06:41
Show Gist options
  • Save unnamedd/941f89a8e4487dd5e91ce3834b38c89a to your computer and use it in GitHub Desktop.
Save unnamedd/941f89a8e4487dd5e91ce3834b38c89a to your computer and use it in GitHub Desktop.
NSTextAttachment
// 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