TTTAttributedLabel 中的一些bug

由于项目需要要求使用可定制的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




 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值