YYTextLayout 计算大小总结

2019-06-09  本文已影响0人  整个夏天

问题

宽度不准确问题

需求为聊天室公屏显示信息,每一条消息的宽度如果没有达到最大宽度则显示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];
上一篇 下一篇

猜你喜欢

热点阅读