TTTAttributedLabel 中的一些bug

来源:互联网 发布:除了暴风影音知乎 编辑:程序博客网 时间:2024/05/22 13:32

由于项目需要要求使用可定制的label,初始方案是用TTTAttributedLabel


其中发现2个bug

1

lineHeightMultiple 小于 1 的时候,text的位置会偏上, 下图设置lineHeightMultiple = 0.5的时候



我的解决方案是在  drawTextInRect 方法中 矩阵变换的时候修改偏移量, 红色为增加部分

    // Inverts the CTM to match iOS coordinates (otherwise text draws upside-down; Mac OS's system is different)    CGRect textRect = rect;    CGFloat yDif = self.font.pointSize * (1 - (_lineHeightMultiple > 0 ? _lineHeightMultiple : 1));    CGContextTranslateCTM(c, 0.0f, textRect.size.height+yDif);    CGContextScaleCTM(c, 1.0f, -1.0f);        CFRange textRange = CFRangeMake(0, [self.attributedText length]);    CFRange fitRange;    // First, adjust the text to be in the center vertically, if the text size is smaller than the drawing rect    CGSize textSize = CTFramesetterSuggestFrameSizeWithConstraints(self.framesetter, textRange, NULL, textRect.size, &fitRange);        if (textSize.height < textRect.size.height) {        CGFloat yOffset = -yDif;        switch (self.verticalAlignment) {            case TTTAttributedLabelVerticalAlignmentTop:                yOffset += yDif;                break;            case TTTAttributedLabelVerticalAlignmentCenter:                yOffset += floorf((textRect.size.height - textSize.height) / 2.0f);                break;            case TTTAttributedLabelVerticalAlignmentBottom:                yOffset += (textRect.size.height - textSize.height);                break;        }                textRect.origin = CGPointMake(textRect.origin.x, textRect.origin.y + yOffset);        textRect.size = CGSizeMake(textRect.size.width, textRect.size.height - yOffset);    }


2

第二个bug是当 numberOfLines = 0; 的时候

typedef enum {

    TTTAttributedLabelVerticalAlignmentCenter   = 0,

    TTTAttributedLabelVerticalAlignmentTop      = 1,

    TTTAttributedLabelVerticalAlignmentBottom   = 2,

} TTTAttributedLabelVerticalAlignment;

 这3个属性不起作用,也就是说text总是画在frame顶部,即使frame size足够大,并设置了TTTAttributedLabelVerticalAlignmentBottom 属性 也不行


跟踪下来发现,原因是

numberOfLines != 0; 的时候,使用CTLineDraw,每行的位置都是算出来的,所以没问题

而numberOfLines==0的时候,使用CTFrameDraw, 这个时候绘制的原点在左下角,绘制的时候从右上角开始,因此TTTAttributedLabelVerticalAlignment计算的偏移量只需要扣除height就好了,

textRect.origin.y 不应该再偏移了


修改方法如下

上面的

        textRect.origin = CGPointMake(textRect.origin.x, textRect.origin.y + yOffset);        textRect.size = CGSizeMake(textRect.size.width, textRect.size.height - yOffset);
改为

textRect.origin = CGPointMake(textRect.origin.x, 0);        textRect.size = CGSizeMake(textRect.size.width, textRect.size.height - yOffset);

ok

done




 

原创粉丝点击