將文本和表情標簽分開,放到數(shù)組里面
- (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];
}
}
創(chuàng)建
- (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];
}
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者