利用YYLabel 進行圖文混排+高度計算


利用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];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM