继承UILabel类实现Label竖直对齐

      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了。





  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值