UILabel如何自定义文字位置(左上?右上?左下?右下?)

来源:互联网 发布:唐小曾软件 编辑:程序博客网 时间:2024/04/29 09:14

我们有时候需要在一个Label上显示文字,而该文字的位置位于Label的左上角,我写个一个小Demo,研究了一下。.h文件#import <UIKit/UIKit.h>typedef enum{    VerticalAlignmentTop = 0,    VerticalAlignmentMiddle,    VerticalAlignmentBottom,} VerticalAlignment;@interface xxxLabel : UILabel@property (nonatomic) VerticalAlignment verticalAlignment;@end.m文件#import "xxxLabel.h"@implementation xxxLabel@synthesize verticalAlignment = verticalAlignment_;- (id)initWithFrame:(CGRect)frame {    if (self = [super initWithFrame:frame]) {        self.verticalAlignment = VerticalAlignmentMiddle;    }    returnself;}- (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:        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


0 0