之前一直沒用YYLabel做過富文本,感覺out了戳护,前兩年面試的時(shí)候就有人問我金抡,可是我很偏執(zhí),或者說對(duì)RichEditor偏執(zhí)腌且,覺得它是最強(qiáng)大的梗肝,別的都不行。但是RichEditor的文檔很少铺董,用的人相對(duì)來說也少巫击,而且寫起來很復(fù)雜,一點(diǎn)也不友好精续,會(huì)有很多坑坝锰,只是因?yàn)槲业谝患夜居玫腞ichEditor,而我會(huì)大概的用法重付,導(dǎo)致了我的不敢用新的東西什黑。其實(shí)現(xiàn)在業(yè)界很熱衷YYLabel,用起來相對(duì)來說簡(jiǎn)單堪夭,作者也是個(gè)中國(guó)人愕把,總得來說YYLabel拣凹,友好,易用恨豁,簡(jiǎn)單嚣镜。
寫了一個(gè)例子,一段文字首尾各插入一張圖片:
_label = [[YYLabel alloc] initWithFrame:CGRectMake(100, 300, 250, 150)];
_label.numberOfLines = 0;
_label.backgroundColor = [UIColor yellowColor];
// _label.preferredMaxLayoutWidth = 250;//我覺得不寫也可以
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"你不錯(cuò)哦 還可以哦我上天是龍下山是上天是龍下山是上天是龍下山是上天是龍下山是虎我是人間堂堂的大英雄我還可以的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
黃色部分就是YYLabel. 首尾各插入了一張圖片,最后讓Label計(jì)算合適的高度橘蜜,效果很好菊匿!