My goal is to store the information for an attributed string in Parse.com. I decided to come up with an encoding for attributed text for my images that works by replacing any string {X}
in braces with the corresponding image. For example:
Picture of 2 colorless mana: {X}
Should produce an attributed string where {X}
is replaced by an image. This is what I've tried:
NSString *formattedText = @"This will cost {2}{PW}{PW} to cast.";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=\\{)[^}]+(?=\\})" options:NSRegularExpressionAnchorsMatchLines
error:nil];
NSArray *matches = [regex matchesInString:formattedText
options:kNilOptions
range:NSMakeRange(0, formattedText.length)];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:formattedText];
for (NSTextCheckingResult *result in matches)
{
NSString *match = [formattedText substringWithRange:result.range];
NSTextAttachment *imageAttachment = [NSTextAttachment new];
imageAttachment.image = [UIImage imageNamed:[NSString stringWithFormat:@"Mana%@.png", match]];
NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
[attributedString replaceCharactersInRange:result.range
withAttributedString:replacementForTemplate];
}
[_textView setAttributedText:attributedString];
There are two problems with this approach currently:
- The braces aren't replaced, only the text inside of them.
- The range for each match is changing because the string itself is changing, and it gets more off with each replacement whose original text was of length > 1. Here's what it looks like: