使用YYLabel小结,供参考

本文介绍使用YYText库实现iOS应用中的图文混排功能。通过具体实例代码展示了如何设置文字样式、插入图片及处理链接点击等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近业务需求需要我们实现图文混排,之前打算使用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值