现在的位置: 首页 > 综合 > 正文

继承UILabel类实现Label竖直对齐

2018年02月23日 ⁄ 综合 ⁄ 共 1927字 ⁄ 字号 评论关闭

      UILabel是个很常见的控件,使用也挺简单的,iOS提供了一系列的设置以方便用户使用——但没竖直方向的对齐。默认的行为是竖直方向自动居中,但有时我们的格式就是要实现竖直的对齐(顶端对齐,底端对齐,中间对齐),虽然有些变通的方法,比如添加\n之类的方法,但仔细考虑觉得还是写一个比较通用的类更方便使用。

     这样一个扩展的继承类实现很简单,直接上代码:

#import <UIKit/UIKit.h>

typedef enum{
    VerticalAlignmentTop = 0,
    VerticalAlignmentMidele,
    VerticalAlignmentBottom,
    VerticalAlignmentMax
}VerticalAlignment;

@interface DPLabel : UILabel
{
    VerticalAlignment _verticalAlignment;
}

@property (nonatomic, assign)VerticalAlignment verticalAlignment;

@end

#import "DPLabel.h"

@implementation DPLabel
@synthesize verticalAlignment;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _verticalAlignment = VerticalAlignmentTop;
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (VerticalAlignment)verticalAlignment
{
    return _verticalAlignment;
}

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

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect rc = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    switch (_verticalAlignment) {
        case VerticalAlignmentTop:
            rc.origin.y = bounds.origin.y;
            break;
        case VerticalAlignmentBottom:
            rc.origin.y = bounds.origin.y + bounds.size.height - rc.size.height;
            break;
        case VerticalAlignmentMidele:
        default:
            rc.origin.y = bounds.origin.y + (bounds.size.height - rc.size.height)/2;
            break;
    }
    
    return rc;
}

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

@end

      这样我们就实现了自己的Label类,并且具有了一个verticalAlignment的属性。使用起来和UILabel没有什么区别


    testLabel = [[DPLabel alloc] initWithFrame:CGRectMake(0, 200, 320, 60)];
    testLabel.text = @"Hello, DPLabel";
    testLabel.backgroundColor = [UIColor whiteColor];
    testLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:testLabel];

        

      这里产生一个新的问题,用IB怎么编辑界面呢?UILabel可以从控件库里面拖过去,DPLabel怎么办呢?答案是设置这个控件的类名,这里就是把选中的控件类名从UILabel改成DPLabel

      

      这样这个功能和UILabel完全兼容,仅增加了竖直对齐的DPLabel继承类就完全可以取代UILabel了。





【上篇】
【下篇】

抱歉!评论已关闭.