显然我解决了。for中有一个代码,用于将子字符串替换为
NSMutableAttributedString
。我还决定把
for
灵感来源于类似(但不同)的问题的先前答案
NSMutableAttributedString *formattedText = myString.mutableAttributedString;
// Look for image
NSString *regEx = @"([a-z])+(?:([0-9])+){0,1}.png";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:regEx
options:NSRegularExpressionCaseInsensitive error:&error];
if(error != nil){
NSLog(@"Error: %@",error);
} else{
NSArray *matches = [regex matchesInString:myString
options:kNilOptions
range:NSMakeRange(0, myString.length)];
for (NSTextCheckingResult *result in [matches reverseObjectEnumerator])
{
NSString *insideString = [myString substringWithRange:[result rangeAtIndex:0]];
UIImage *image = [UIImage imageNamed:insideString];
NSTextAttachment *imageAttachment = [NSTextAttachment new];
imageAttachment.image = image;
NSAttributedString *replacementForTemplate = [NSAttributedString attributedStringWithAttachment:imageAttachment];
[formattedText replaceCharactersInRange:result.range
withAttributedString:replacementForTemplate];
NSLog(@"found! -> %@", insideString);
}
}
相反
mutableAttributedString
属性属于NSString类别。这是它的代码
- (NSMutableAttributedString *)mutableAttributedString {
return [[NSMutableAttributedString alloc] initWithString:self];
}