当UILabel单行的时候,设置文字的位置

#import 

typedef NS_ENUM(NSInteger,TextVerticalAlignment){
    TextVerticalAlignmentTop = 0, //当文字是单行的时候,文字是居上的而不是默认的居中,解决Label与上面控件的间距扩大的问题
    TextVerticalAlignmentMiddle,
    TextVerticalAlignmentBottom,
};


@interface TextVerticalAlignmentLabel : UILabel
@property (nonatomic) TextVerticalAlignment verticalAlignment;
@end
#import "TextVerticalAlignmentLabel.h"

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

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

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
    CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    switch (self.verticalAlignment) {
        case TextVerticalAlignmentTop:
            textRect.origin.y = bounds.origin.y;
            break;
        case TextVerticalAlignmentBottom:
            textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
            break;
        case TextVerticalAlignmentMiddle:
            
        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单行的时候,设置文字的位置)