最近在使用textView顯示富文本粘勒,需求是實(shí)現(xiàn)部分文字顯示不同顏色,支持點(diǎn)擊鏈接跳轉(zhuǎn),支持動(dòng)態(tài)高度马僻。
部分文字顯示不同顏色
[attStr addAttribute:NSForegroundColorAttributeName value:COLOR(66, 140, 241, 1) range:self.productRange];
添加鏈接
[attStr addAttribute:NSLinkAttributeName value:model.url range:self.productRange]; ? ? ? ? ? ? self.contentLabel.linkTextAttributes = @{NSForegroundColorAttributeName:COLOR(66, 140, 241, 1)}; // 修改可點(diǎn)擊文字的顏色
//實(shí)現(xiàn)代理方法录语,return yes 會(huì)使用safari打開鏈接
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange { ? ?
if (characterRange.location == self.productRange.location) { ? ? ? ?
//自定義動(dòng)作
} ? ?
return NO;?
}
回到標(biāo)題內(nèi)容倍啥,計(jì)算textView內(nèi)容高度
相信大家都會(huì)計(jì)算label的多行文字高度,textView的用法也一樣澎埠,boundingRectWithSize
CGSize size = [self.contentLabel.attributedText.string boundingRectWithSize:CGSizeMake(Size(270) - 2 * leftPadding, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:Size(14)]} context:nil].size;
但是在textView顯示多行文字時(shí)虽缕,用以上方法會(huì)出現(xiàn)最后一行顯示不全,也就是計(jì)算的高度不對蒲稳,通過視圖工具可以看見textContainer的高度是比textView的高度要大的氮趋,由于每一行開頭結(jié)尾textView都會(huì)有padding,導(dǎo)致計(jì)算高度時(shí)的參數(shù)----計(jì)算的寬度比實(shí)際寬度要大江耀,計(jì)算出來的高度也就要小一些剩胁,因此傳入的寬度要減去兩邊的padding
解決方案:boundingRectWithSize 中的寬度減去兩邊的padding
CGFloat leftPadding = self.contentLabel.textContainer.lineFragmentPadding;