美文网首页
自定义UILabel,添加verticalAlignment属性

自定义UILabel,添加verticalAlignment属性

作者: i诺离 | 来源:发表于2017-12-13 14:00 被阅读121次

效果

  • -----bottom 屏幕快照 2017-12-13 下午1.58.47.png

代码:

@synthesize verticalAlignment = _verticalAlignment;

- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment
{
    _verticalAlignment = verticalAlignment;
    [self setNeedsDisplay];
}

- (void)drawTextInRect:(CGRect)rect
{
    CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
    [super drawTextInRect:actualRect];
}

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];// 获取文字的rect
    textRect = CGRectMake(bounds.origin.x, textRect.origin.y, bounds.size.width, textRect.size.height);// 微调
    
    switch (self.verticalAlignment) {
        case KLTextVerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case KLTextVerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case KLTextVerticalAlignmentMiddle:
            // Fall through.
        default:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
            break;
    }

    return textRect;
}

相关文章

网友评论

      本文标题:自定义UILabel,添加verticalAlignment属性

      本文链接:https://www.haomeiwen.com/subject/hhiaixtx.html