美文网首页
利用YYLabel实现评论图文混排功能

利用YYLabel实现评论图文混排功能

作者: 一个无知的码农 | 来源:发表于2018-06-07 10:22 被阅读0次

UILabel有专门的计算文字高度的方法,非常简单/*

 *titleString 传入的内容

 *font 字体的大小

 *height 如果计算宽度,传入高度, 如果计算高度,就传入宽度

 */  

+(float)judgeTheLabelWidthWithString:(NSString *)titleString andWithThefont:(NSInteger)font andwiththeheighth:(NSInteger)height{

UIFont * sizeFont;  

if ([Version floatValue] >=9) {  

        sizeFont = CustomFont(font);  

}else{ 

    sizeFont = [UIFont systemFontOfSize:font];  

    }  

NSDictionary *dic = @{NSFontAttributeName:sizeFont};  //指定字号  

//MAXFLOAT 常量 最大值  

CGRect rect = [titleString boundingRectWithSize:CGSizeMake(MAXFLOAT, height)  options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil];  

return rect.size.width;   

以上方法只能使用纯文字,字体的大小确定才能准确的计算出高度,从而设定label的高度

当内容中有图片的时候计算时就会出现计算不准确,从而无法布局。

YYLabel 是一个专门用于图文混排的第三方插件,利用NSAttributedString将文字和图片拼接在一起,(图片会用\U0000fffcz占位符实现)从而显示出来。

YYLabel中有一个YYLayout和YYTextContainer2个类,可以利用这2个类来进行富文本的高度计算,代码如下

NSMutableAttributedString * content = [PublicAction processCommentContent:replacString];  

YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(ScreenWidth- 50, MAXFLOAT)];  

YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:content];  

textLayout有一个属性 textBoundingSize.height,这个高度就是计算出来的准确高度

https://github.com/search?utf8=✓&q=YYLabelText

相关文章

网友评论

      本文标题:利用YYLabel实现评论图文混排功能

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