iOS开发之----让UILabel 垂直方向顶端对齐的代码

来源:互联网 发布:excel导入mdb数据库 编辑:程序博客网 时间:2024/06/12 05:20
原文地址:IOS开发之----让UILabel 垂直方向顶端对齐的代码作者:倒計時

VerticalAlignment.h文件


#import <UIKit/UIKit.h>


typedef enum VerticalAlignment {

    VerticalAlignmentTop,

    VerticalAlignmentMiddle,

    VerticalAlignmentBottom,

} VerticalAlignment;


@interface VerticallyAlignedLabel : UILabel

{

@private VerticalAlignment verticalAlignment_;

}


@property (nonatomicassignVerticalAlignment verticalAlignment;

@end




VerticalAlignment.m文件


 


#import "VerticallyAlignedLabel.h"


@implementation VerticallyAlignedLabel


@synthesize verticalAlignment = verticalAlignment_;


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self) {

        // Initialization code

    }

    return self;

}


- (void)setVerticalAlignment:(VerticalAlignment)verticalAlignment {

    verticalAlignment_ = verticalAlignment;

    [self setNeedsDisplay];

}


- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {

    CGRect textRect = [super textRectForBounds:boundslimitedToNumberOfLines: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:requestedRectlimitedToNumberOfLines:self.numberOfLines];

    [super drawTextInRect:actualRect];

}


@end

0 0
原创粉丝点击