之前一直没用YYLabel做过富文本,感觉out了,前两年面试的时候就有人问我,可是我很偏执,或者说对RichEditor偏执,觉得它是最强大的,别的都不行。但是RichEditor的文档很少,用的人相对来说也少,而且写起来很复杂,一点也不友好,会有很多坑,只是因为我第一家公司用的RichEditor,而我会大概的用法,导致了我的不敢用新的东西。其实现在业界很热衷YYLabel,用起来相对来说简单,作者也是个中国人,总得来说YYLabel,友好,易用,简单。
写了一个例子,一段文字首尾各插入一张图片:
_label = [[YYLabel alloc] initWithFrame:CGRectMake(100, 300, 250, 150)];
_label.numberOfLines = 0;
_label.backgroundColor = [UIColor yellowColor];
// _label.preferredMaxLayoutWidth = 250;//我觉得不写也可以
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"你不错哦 还可以哦我上天是龙下山是上天是龙下山是上天是龙下山是上天是龙下山是虎我是人间堂堂的大英雄我还可以的over"];
YYAnimatedImageView *imgView1 = [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"a"]];
imgView1.frame = CGRectMake(0, 0, 20, 20);
YYAnimatedImageView *imgView2 = [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"b"]];
imgView1.frame = CGRectMake(0, 0, 20, 20);
NSMutableAttributedString *attchText1 = [NSMutableAttributedString attachmentStringWithContent:imgView1 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imgView1.frame.size alignToFont:[UIFont systemFontOfSize:20] alignment:YYTextVerticalAlignmentCenter];
NSMutableAttributedString *attchText2 = [NSMutableAttributedString attachmentStringWithContent:imgView2 contentMode:UIViewContentModeScaleAspectFit attachmentSize:imgView2.frame.size alignToFont:[UIFont systemFontOfSize:20] alignment:YYTextVerticalAlignmentCenter];
[attr insertAttributedString:attchText1 atIndex:0];
[attr appendAttributedString:attchText2];
_label.attributedText = attr;
CGSize maxSize = CGSizeMake(250, MAXFLOAT);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:attr];
_label.textLayout = layout;
CGFloat introHeight = layout.textBoundingSize.height;
_label.width = 250;
_label.height = introHeight;
[self.view addSubview:_label];
效果图:

黄色部分就是YYLabel. 首尾各插入了一张图片,最后让Label计算合适的高度,效果很好!
网友评论