自定义UILabel(垂直方向布局)

//
//  CKLabel.h
//  ShoppingProject
//
//  Created by CK on 15/12/10.
//  Copyright © 2015年 GuanYisoft. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef enum
{
    VerticalAlignmentTop = 0, //垂直方向上对齐
    VerticalAlignmentMiddle,  //垂直方向居中
    VerticalAlignmentBottom,  //垂直方向下对齐
} VerticalAlignment; 
@interface CKLabel : UILabel
@property (nonatomic) VerticalAlignment verticalAlignment; //label的垂直方向方向
@end


/**************************************************************************/

//
//  CKLabel.m
//  ShoppingProject
//
//  Created by CK on 15/12/10.
//  Copyright © 2015年 GuanYisoft. All rights reserved.
//

#import "CKLabel.h"

@implementation CKLabel

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.verticalAlignment = VerticalAlignmentMiddle;
    }
    return self;
}

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

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    switch (self.verticalAlignment) {
        case VerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case VerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case VerticalAlignmentMiddle:
            // Fall through.
        default:
            textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
    }
    return textRect;
}

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

@end


你可能感兴趣的:(自定义UILabel(垂直方向布局))