前言:我們規(guī)定字符串中的表情以"["開始,"]"結(jié)尾。
1.首先我們分析一個(gè)字符串判斷哪些是表情,哪些是文字然后加入一個(gè)數(shù)組中待用。
- (void)getMessageRange:(NSString*)message :(NSMutableArray*)array {
NSRange range=[message rangeOfString: @"["];
NSRange range1=[message rangeOfString: @"]"];
//判斷當(dāng)前字符串是否還有表情的標(biāo)志赊时。
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 getMessageRange:str :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 getMessageRange:str :array];
}else {
return;
}
}
} else if (message != nil) {
[array addObject:message];
}
}
2.對得到的數(shù)組進(jìn)行分析
NSMutableArray *contentArray = [NSMutableArray array];
[self getMessageRange:@"你需要顯示的字符串" :contentArray];
NSMutableAttributedString *strM = [[NSMutableAttributedString alloc] init];
for (NSString *object in contentArray) {
NSLog(@"%@",object);
if ([object hasSuffix:@"]"]&&[object hasPrefix:@"["]) {
//如果是表情用iOS中附件代替string在label上顯示
NSTextAttachment *imageStr = [[NSTextAttachment alloc]init];
imageStr.image = [UIImage imageNamed:[object substringWithRange:NSMakeRange(1, object.length - 2)]];
//這里對圖片的大小進(jìn)行設(shè)置一般來說等于文字的高度
CGFloat height = self.label.font.lineHeight;
imageStr.bounds = CGRectMake(0, 0, height, height);
NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:imageStr];
[strM appendAttributedString:attrString];
}else{
//如果不是表情直接進(jìn)行拼接
[strM appendAttributedString:[[NSAttributedString alloc] initWithString:object]];
}
}
self.label.attributedText = strM;