美文网首页表情
iOS中类似QQ聊天表情的显示(图文混排)

iOS中类似QQ聊天表情的显示(图文混排)

作者: SacredBillows | 来源:发表于2016-05-19 11:06 被阅读1122次

    前言:我们规定字符串中的表情以"["开始,"]"结尾。

    1.首先我们分析一个字符串判断哪些是表情,哪些是文字然后加入一个数组中待用。

    - (void)getMessageRange:(NSString*)message :(NSMutableArray*)array {

    NSRange range=[message rangeOfString: @"["];

    NSRange range1=[message rangeOfString: @"]"];

    //判断当前字符串是否还有表情的标志。

    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.对得到的数组进行分析

    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)]];

    //这里对图片的大小进行设置一般来说等于文字的高度

    CGFloat height = self.label.font.lineHeight;

    imageStr.bounds = CGRectMake(0, 0, height, height);

    NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:imageStr];

    [strM appendAttributedString:attrString];

    }else{

    //如果不是表情直接进行拼接

    [strM appendAttributedString:[[NSAttributedString alloc] initWithString:object]];

    }

    }

    self.label.attributedText = strM;

    相关文章

      网友评论

        本文标题:iOS中类似QQ聊天表情的显示(图文混排)

        本文链接:https://www.haomeiwen.com/subject/qcqgrttx.html