iOS技术资料iOS Developer实用工具

利用YYLabel 进行图文混排+高度计算

2017-05-02  本文已影响8778人  吴佩在天涯

利用YYLabel 进行图文混排+高度计算

1、项目需求:

用一个控件显示图片和文字,并且依据图片和文字动态计算控件的高度。

2、方案:

利用YYLabel控件和属性字符串处理。

注:(在使用YYLabel之前,使用UILabel测试过,但是发现在图文混排的时候。利用属性字符串计算高度不太准确。会有多余的文字不显示。)

示例代码

//使用YYText 处理富文本行高

YYLabel *contentL = [[YYLabel alloc] init];
//设置多行
contentL.numberOfLines = 0;
//这个属性必须设置,多行才有效
contentL.preferredMaxLayoutWidth = kScreenWidth -32;

 NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithAttributedString:[OSCBaseCommetView contentStringFromRawString:commentItem.content withFont:24.0]];

//可以将要插入的图片作为特殊字符处理
//需要使用 YYAnimatedImageView 控件,直接使用UIImage添加无效。

YYAnimatedImageView *imageView1= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"ic_quote_left"]];
imageView1.frame = CGRectMake(0, 0, 16, 16);

YYAnimatedImageView *imageView2= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"ic_quote_right"]];
imageView2.frame = CGRectMake(0, 0, 16, 16);
// attchmentSize 修改,可以处理内边距
NSMutableAttributedString *attachText1= [NSMutableAttributedString attachmentStringWithContent:imageView1 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView1.frame.size alignToFont:[UIFont systemFontOfSize:24] alignment:YYTextVerticalAlignmentCenter];

NSMutableAttributedString *attachText2= [NSMutableAttributedString attachmentStringWithContent:imageView2 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageView2.frame.size alignToFont:[UIFont systemFontOfSize:24] alignment:YYTextVerticalAlignmentCenter];

 //插入到开头
[attri insertAttributedString:attachText1 atIndex:0];
 //插入到结尾
[attri appendAttributedString:attachText2];

//用label的attributedText属性来使用富文本
contentL.attributedText = attri;

CGSize maxSize = CGSizeMake([UIScreen mainScreen].bounds.size.width - 32, MAXFLOAT);

//计算文本尺寸
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attri];
contentL.textLayout = layout;
CGFloat introHeight = layout.textBoundingSize.height;


contentL.frame =  commentItem.layoutInfo.contentTextViewFrame;
contentL.width = maxSize.width;

contentL.height = introHeight + 50;

[self addSubview:contentL];

最终效果

屏幕快照 2017-05-02 下午6.00.31.png

参考链接:

http://www.jianshu.com/p/e6d4b2f96b4c

上一篇下一篇

猜你喜欢

热点阅读