使用YYLabel小结,供参考

简介: 最近业务需求需要我们实现图文混排,之前打算使用UIlabel自带的属性attributedText,这个属性也很强大,可以实现图文混排,但是发现,实现链接点击有些困难,于是放弃。

最近业务需求需要我们实现图文混排,之前打算使用UIlabel自带的属性attributedText,这个属性也很强大,可以实现图文混排,但是发现,实现链接点击有些困难,于是放弃。再后来发现了一个TTTAttributedLabel,他继承自UIlabel,但是使用的过程中发现,这个三方对链接支持是可以的,而对图片是不支持的,这让我一度纠结。之后,下定决心,重绘UI,重新选择,最终选择了YYText,实践发现,图文混排还是YYText好用啊。YYText继承自UIView,也实现了UILabel的很多功能和属性,真的很强大,不说了,直接上代码吧。

  YYLabel * commentLabel =[YYLabel new];
    commentLabel.numberOfLines = 3;//限制三行
    commentLabel.lineBreakMode = NSLineBreakByTruncatingTail;
    //这个属性必须设置,多行才有效
    commentLabel.preferredMaxLayoutWidth = mScreenWidth -20;
    NSMutableAttributedString  *titleAttr = [self getAttrWithData:commentData];
    commentLabel.attributedText  = titleAttr;

getAttrWithData这个方法主要是对文字进行排版属性的设置,代码中包含我们自己的一些业务逻辑,所以,需要的小伙伴们可以参考一下。
为了方便大家看,这个方法有很多行,没有拆分,实际使用的时候,大家尽量还是拆分一下,一个方法不要超过100行比较好。

- (NSMutableAttributedString*)getAttrWithData:(JZCommunityListPostCommentsModel *)model{
    NSString * attributedString = [NSString stringWithFormat:@"%@:%@",model.author.name,model.content];
    NSMutableAttributedString * resultAttr = [[NSMutableAttributedString alloc] initWithString:attributedString];
    
    //对齐方式 这里是 两边对齐
    resultAttr.yy_alignment = NSTextAlignmentLeft;
    //设置行间距
    resultAttr.yy_lineSpacing = 5;
    //设置字体大小
    resultAttr.yy_font = [UIFont systemFontOfSize:13];
    //设置作者的文字颜色
    NSRange authorRange = [attributedString rangeOfString:model.author.name];
    [resultAttr yy_setTextHighlightRange:authorRange color:[UIColor colorFromRGB:0x999999] backgroundColor:nil userInfo:nil];
    //处理topic----我们自己业务
    for (int i= 0; i<model.at_topics_content.count; i++) {
        NSDictionary * dict = model.at_topics_content[i];
        NSRange topicRange = [[resultAttr string]rangeOfString:[NSString stringWithFormat:@"<!--TOPIC#%d-->",i]];
        if (topicRange.length>0) {//说明有话题
            NSString * replaceStr = [NSString stringWithFormat:@"#%@%d#",dict[@"title"],i];
            [resultAttr replaceCharactersInRange:topicRange withString:replaceStr];
            NSRange replaceRan = [[resultAttr string]rangeOfString:replaceStr];
            NSRange replaceRange = NSMakeRange(replaceRan.location, replaceRan.length-1);
            NSString * replaceString = [NSString stringWithFormat:@"#%@#",dict[@"title"]];
            [resultAttr replaceCharactersInRange:replaceRan withString:replaceString];
            
            //修改话题的颜色
            [resultAttr yy_setTextHighlightRange:replaceRange color:[UIColor colorFromRGB:0xfc5f59] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                NSString * clickStr = [[text string] substringWithRange:range];
                for (NSDictionary * dict in model.at_topics_content) {
                    NSString * title = [NSString stringWithFormat:@"#%@#",dict[@"title"]];                    
                    if ([title isEqualToString:clickStr]) {
                        //根据urlroute跳到话题页
                        if ([dict.allKeys containsObject:@"urlroute"]) {
                            NSString * urlRoute = dict[@"urlroute"];
                            [JZRouter routeURL:urlRoute];
                        }
                         break;
                    }
                }
            }];
        }
    }
    
    //处理图片 img
    for (int i = 0; i<model.img.count; i++) {
        NSString * imageStr = [NSString stringWithFormat:@"<!--IMG#%d-->",i];
        NSRange imageRange = [[resultAttr string] rangeOfString:imageStr];
        if (imageRange.length>0) {//有图片,处理图片
            NSString * strimg = [NSString stringWithFormat:@"查看图片%d",i];
            [resultAttr replaceCharactersInRange:imageRange withString:strimg];
            NSRange strRange = [[resultAttr string] rangeOfString:strimg];
            
            //插入图片
            UIImage *image = [UIImage imageNamed:@"community_checkImage"];
            NSMutableAttributedString *attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:[UIFont systemFontOfSize:13] alignment:YYTextVerticalAlignmentCenter];
            [resultAttr insertAttributedString:attachment atIndex:strRange.location];
            NSRange linkRange = NSMakeRange(strRange.location, strRange.length+1);
            //把数字文字变小,且变成白色,隐藏起来
            NSInteger loca = linkRange.location + linkRange.length -1;
            NSRange numRange = NSMakeRange(loca, 1);
            [resultAttr yy_setFont:[UIFont systemFontOfSize:1] range:numRange];
            [resultAttr yy_setColor:[UIColor whiteColor] range:numRange];
            __weak JZCommunityBigImageCell * weakSelf = self;
            [resultAttr yy_setTextHighlightRange:linkRange color:[UIColor colorFromRGB:0xfc5f59] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                NSString * clickStr = [[text string] substringWithRange:range];
                NSString * numStr = [clickStr substringFromIndex:5];
                NSInteger index = [numStr integerValue];
                if (index<model.img.count) {
                    NSString *imageUrl = model.img[index];
                    NSArray * array = @[imageUrl];
                    [weakSelf showPhotoGallary:array withSrc:imageUrl];
                }
            }];
        }
    }
    
    return resultAttr;
    
}

小结一下:整理一下,和YYLabel相关的设置如下

-(void)manageYYLabelOne{
   //设置链接,添加图片
    NSString * title = @"小明说:我是一个yytextLabel,我要实现富媒体。之前实现富媒体的方法不够好,这次一定要成功!之前实现富媒体的方法不够好,这次一定要成功!之前实现富媒体的方法不够好,之前实现富媒体的方法不够好,之前实现富媒体的方法不够好,之前实现富媒体的方法不够好,之前实现富媒体的方法不够好,之前实现富媒体的方法不够好,";
    //之前实现富媒体的方法不够好,这次一定要成功!
    self.yyLabelOne.numberOfLines = 3;
    self.yyLabelOne.lineBreakMode = NSLineBreakByTruncatingTail;
    //这个属性必须设置,多行才有效
    self.yyLabelOne.preferredMaxLayoutWidth = kScreenWidth -20;
    YYTextContainer * container = [YYTextContainer new];
    //限制宽度
    container.size             = CGSizeMake(kScreenWidth-20,CGFLOAT_MAX);
    NSMutableAttributedString  *titleAttr = [self getAttr:title];
    YYTextLayout *titleLayout = [YYTextLayout layoutWithContainer:container text:titleAttr];
    
    CGFloat titleLabelHeight = titleLayout.textBoundingSize.height;
    if (titleLabelHeight>51) {//大于三行,显示三行的高度
        titleLabelHeight = 51;
    }
    self.yyLabelOne.frame = CGRectMake(10,50,[UIScreen mainScreen].bounds.size.width-20,titleLabelHeight);
    self.yyLabelOne.attributedText  = titleAttr;
    
}

- (NSMutableAttributedString*)getAttr:(NSString*)attributedString {
    NSMutableAttributedString * resultAttr = [[NSMutableAttributedString alloc] initWithString:attributedString];
    
    //对齐方式 这里是 两边对齐
    resultAttr.yy_alignment = NSTextAlignmentLeft;
    //设置行间距
    resultAttr.yy_lineSpacing = 5;
    //设置字体大小
    resultAttr.yy_font = [UIFont systemFontOfSize:13];
    //设置连接文字
    [resultAttr yy_setTextHighlightRange:NSMakeRange(3, 3) color:[UIColor redColor] backgroundColor:nil tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSLog(@"这是一个连接   %@",[text string]);
    }];
    //设置特殊文字颜色
    [resultAttr yy_setTextHighlightRange:NSMakeRange(0, 3) color:[UIColor greenColor] backgroundColor:nil userInfo:nil];
    
    //添加图片
    UIImage *image = [UIImage imageNamed:@"community_checkImage"];
    NSMutableAttributedString *attachment = nil;
    attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:[UIFont systemFontOfSize:13] alignment:YYTextVerticalAlignmentCenter];
    //[resultAttr appendAttributedString: attachment];
    [resultAttr insertAttributedString:attachment atIndex:3];
    
    //可以设置某段字体的大小
    //[resultAttr yy_setFont:[UIFont boldSystemFontOfSize:CONTENT_FONT_SIZE] range:NSMakeRange(0, 3)];
    //设置字间距
    //resultAttr.yy_kern = [NSNumber numberWithFloat:1.0];
    
    return resultAttr;
    
}

实现效果如下:(备注:背景色是xib上画的,代码中没有;图片是本地的)。

img_d5818d56c06239af1056f937ca94b441.png
image.png
目录
相关文章
|
9月前
|
JSON 测试技术 API
【测试平台系列】第一章 手撸压力机(十一)-初步实现性能测试
上一章节我们组合了场景,它是一个list结构。今天我们实现性能测试计划的数据结构及其方法.
|
10月前
Axure快速入门(02) - 入门例子(登录案例)
Axure快速入门(02) - 入门例子(登录案例)
52 0
小马识途简析创建百科词条的流程和注意事项
小马识途简析创建百科词条的流程和注意事项
145 0
|
关系型数据库 MySQL 数据库
2022最新mysql安装与配置教程(简单易懂,图文解释)
2022最新mysql安装与配置教程(简单易懂,图文解释)
635 0
2022最新mysql安装与配置教程(简单易懂,图文解释)
|
JSON 数据格式 iOS开发
【Axure教程】函数自查表(全攻略)(下)
【Axure教程】函数自查表(全攻略)
|
弹性计算 固态存储 数据安全/隐私保护
【评测】真香,十分钟基于阿里云ECS计算型 c5服务器搭建个人博客--附上详细步骤
前言 hi,大家好,近期参加了阿里云的ECS评测活动,有幸获得了一台ECS计算型 c5云服务器。直接拉满开造! ECS服务器介绍 阿里云服务器ECS计算型c5实例CPU处理器采用2.5 GHz主频的Intel ® Xeon ® Platinum 8163(Skylake)或者8269CY(Cascade Lake),计算性能稳定,I/O优化实例,支持ESSD云盘、SSD云盘和高效云盘,处理器与内存配比为1:2,超高网络PPS收发包能力。
544 0
【评测】真香,十分钟基于阿里云ECS计算型 c5服务器搭建个人博客--附上详细步骤
|
数据采集 JSON 数据格式
You-Get开源在线下载神器,搭配python更加丝滑(文中案例演示)
介绍一个号称可以下载全网视频、音频、图像的开源库
424 0
You-Get开源在线下载神器,搭配python更加丝滑(文中案例演示)
阿里云怎么使用?网站上线必备步骤
很多新用户朋友出于某些原因,购买了阿里云服务器,但是买来后,发现只是一个空白的服务器,没有安装任何服务器运行环境,比如程序语言,数据库,FTP等,不知道怎么用!下面简单介绍下小白用户将服务器买来之后,搭建我们的网站还需要做什么?建站所必须:域名、服务器、程序源码一. 域名: 注册好域名,注册地址:https://wanwang.aliyun.com/?spm=5176.8142029.selected.4.e9396d3eyvDwRn 并给域名做好实名认证。