问题
-
YYTextLayout
在计算带有\n
字符串高度的时候出现宽度不准确的问题 - 第一个字符为图片的时候,第一行字符高度不准确
宽度不准确问题
需求为聊天室公屏显示信息,每一条消息的宽度如果没有达到最大宽度则显示label
的实际宽度,高度为默认的一行高度22
,如果超过了最大的宽度则说明需要换行,以最大宽度为基准计算高度
//这里的计算基准高度也给最大值即可
YYTextLayout *layoutWidth = [YYTextLayout layoutWithContainerSize:CGSizeMake(CGFLOAT_MAX, 22) text:self.attributedString];
if (layoutWidth.textBoundingSize.width>maxW) {
//
YYTextLayout *layoutH = [YYTextLayout layoutWithContainerSize:CGSizeMake(maxW, CGFLOAT_MAX) text:self.attributedString];
labelH=layoutWidth.textBoundingSize.height;
labelW=maxW;
}else{
labelH=22;
labelW=layoutWidth.textBoundingSize.width;
}
这里在带有\n
字符串的时候就会出现问题,YYTextLayout
在计算字符串宽度的时候是先算有多少行,在算出每行的宽度,取最大值为字符串的宽度。
这里在计算宽度的时候给的高度是22
,则只会计算第一行的宽度,正常文字第一行肯定即为最大宽度,而带换行符的字符串第一行未必为最大的宽度,则会出现宽度计算错误的问题,将计算宽度的高度基准22
改为最大值即可解决。
第一行字符高度不准确
在第一个字符为图片的时候,会导致第一行的高度即为图片的设置高度,目前还不明白是如何计算导致了这个问题,只能换个思路解决。
即在imageView
的外面套一层view
,将view
的高度设为每一行的高度来显示出行间距,根据需求也可以将view
的宽度设大一些来预留出文字和图片的左右间距
YYAnimatedImageView *imageView= [[YYAnimatedImageView alloc] initWithImage:[UIImage imageNamed:@"level_default"]];
imageView.frame = CGRectMake(4, 3, self.imgViewLevelSize.width, self.imgViewLevelSize.height);
CGRect rect=CGRectMake(0, 0, self.imgViewLevelSize.width+8, 21);
UIView * parent =[[UIView alloc] initWithFrame:rect];
[parent addSubview:imageView];
NSMutableAttributedString *attachImg= [NSMutableAttributedString yy_attachmentStringWithContent:parent contentMode:UIViewContentModeScaleAspectFit attachmentSize:parent.frame.size alignToFont:self.font alignment:YYTextVerticalAlignmentCenter];
[self.attributedString insertAttributedString:attachImg atIndex:index];
网友评论