将文本和表情标签分开,放到数组里面
- (void)getImageRange:(NSString *)message array:(NSMutableArray *)array
{
NSRange range=[message rangeOfString:kImageBeginMark];
NSRange range1=[message rangeOfString:kimageEndMark];
//判断当前字符串是否还有表情的标志。
if (range.length>0 && range1.length>0)
{
if (range.location > 0)
{
[array addObject:[message substringToIndex:range.location]];
[array addObject:[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)]];
NSString *str=[message substringFromIndex:range1.location+1];
[self getImageRange:str array:array];
}
else
{
NSString *nextstr=[message substringWithRange:NSMakeRange(range.location, range1.location+1-range.location)];
//排除文字是“”的
if (![nextstr isEqualToString:@""])
{
[array addObject:nextstr];
NSString *str=[message substringFromIndex:range1.location+1];
[self getImageRange:str array:array];
}
else
{
return;
}
}
}
else if (message != nil)
{
[array addObject:message];
}
}
创建
- (id)initWithText:(NSString *)text
{
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineSpacing = 4;
paragraph.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary *attributes = @{NSFontAttributeName : [UIFont systemFontOfSize:16],
NSParagraphStyleAttributeName : paragraph};
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@""];
NSMutableArray *array = [[NSMutableArray alloc] init];
[self getImageRange:text array:array];
for (NSString *item in array)
{
if ([item hasPrefix:kImageBeginMark] && [item hasSuffix:kimageEndMark])
{
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
[textAttachment setImage:[UIImage imageNamed:item]];
[textAttachment setBounds:CGRectMake(0, -5, 25, 25)];
NSAttributedString *attrStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
[string appendAttributedString:attrStr];
}
else
{
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:item attributes:attributes];
[string appendAttributedString:attrStr];
}
}
}