int size=0;
NSString *s = @"12345[tym_123]6789101[tym_323]112";
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:s attributes:nil];
//
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\[tym_)\\d{3}(\\])" options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *array = nil;
array = [regex matchesInString:s options:0 range:NSMakeRange(0, [s length])];
NSString *str1 = nil;
for (NSTextCheckingResult* b in array)
{
NSLog(@"%d",string.length);
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
UIImage *smileImage = [UIImage imageNamed:@"aaa.png"]; //my emoticon image named a.jpg
textAttachment.image = smileImage;
NSAttributedString *textAttachmentString = [NSAttributedString attributedStringWithAttachment:textAttachment];
NSRange r = b.range;
r.location = r.location -size;
[string replaceCharactersInRange:r withAttributedString:textAttachmentString];
size+=8;//每个图片占8位
}
_txtTextAndImage.attributedText = string;
转载于:https://my.oschina.net/u/564793/blog/418785