系统中的UILabel对齐方式只有左、中、右对齐方式,有时候希望文本内容上部、中间和底部对齐,所以下面自定义一个继承UILabel的类来实现上部、中间和底部对齐。先来看一下.h文件:
.h 文件
typedef NS_ENUM (NSInteger ,VerticalAlignment){
VerticalAlignmentTop = 0, //上居中
VerticalAlignmentMiddle, //中居中
VerticalAlignmentBottom //低居中
};
@interface VerticalLabel : UILabel
@property (nonatomic,assign)VerticalAlignment verticalAlignment;
@end
.m文件
@implementation VerticalLabel
-(instancetype)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 = self.bounds.origin.y;
break;
case VerticalAlignmentMiddle:
break;
case VerticalAlignmentBottom:
textRect.origin.y = bounds.origin.y + bounds.size.height - textRect.size.height;
break;
default:
textRect.origin.y = bounds.origin.y + (bounds.size.height - textRect.size.height) / 2.0;
break;
}
return textRect;
}
-(void)drawTextInRect:(CGRect)rect{
CGRect actualRect = [self textRectForBounds:rect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
使用此类:请看下面的使用的例子
VerticalLabel *textLabel = [[VerticalLabel alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
textLabel.numberOfLines = 1;
textLabel.font = [UIFont systemFontOfSize:18];
textLabel.text = @"哈哈哈哈哈";
textLabel.textColor = [UIColor redColor];
textLabel.backgroundColor = [UIColor greenColor ];
textLabel.verticalAlignment = VerticalAlignmentTop;
textLabel.textAlignment = NSTextAlignmentRight;
[self.view addSubview:textLabel];
搭配系统的属性textAlignment,可以组成左上角对齐,右上角对齐,左居中对齐,右居中对齐,左下角对齐,右下角对齐,居中。