码迷,mamicode.com
首页 > 移动开发 > 详细

iOS的UILabel设置居上对齐,居中对齐,居下对齐

时间:2015-05-10 23:39:02      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

在iOS中默认的UILabel中的文字在竖直方向上只能居中对齐,我从UILabel继承了一个新类,实现了居上对齐,居中对齐,居下对齐。具体如下:

1.新建一个类VerticalAlignmentLabel.h继承自UILabel

2.

//

//  VerticalAlignmentLabel.h

//  inface

//

//  Created by huangzengsong on 15/5/10.

//  Copyright (c) 2015年 huangzs. All rights reserved.

//

 

#import <UIKit/UIKit.h>

 

 

typedef enum

{

    VerticalAlignmentTop = 0, // default

    VerticalAlignmentMiddle,

    VerticalAlignmentBottom,

} VerticalAlignment;

@interface VerticalAlignmentLabel : UILabel

 

{

@private

    VerticalAlignment _verticalAlignment;

}

 

@property (nonatomic) VerticalAlignment verticalAlignment;

 

@end

 

3.

//

//  VerticalAlignmentLabel.m

//  inface

//

//  Created by huangzengsong on 15/5/10.

//  Copyright (c) 2015年 huangzs. All rights reserved.

//

 

#import "VerticalAlignmentLabel.h"

 

@implementation VerticalAlignmentLabel

@synthesize verticalAlignment = verticalAlignment_;

 

- (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];

}

 

 

 

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    // Drawing code

}

*/

 

@end

 

4.调用时导入头文件

#import "VerticalAlignmentLabel.h"

5.

[self.DetailLabel setVerticalAlignment:VerticalAlignmentTop];

 

iOS的UILabel设置居上对齐,居中对齐,居下对齐

标签:

原文地址:http://www.cnblogs.com/huangzs/p/4493173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!