iOS的UILabel设置上部对齐,中间对齐,底部对齐
.h 文件
typedef NS_ENUM (NSInteger ,VerticalAlignment){
VerticalAlignmentTop = 0, //上居中
VerticalAlignmentMiddle, //中居中
VerticalAlignmentBottom //低居中
};
@interface VerticalLabel : UILabel
{
@private
VerticalAlignment _verticalAlignment;
}
@property (nonatomic,assign)VerticalAlignment verticalAlignment;
@end
.m文件
@implementation VerticalLabel
@synthesize verticalAlignment = _verticalAlignment;
-(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,可以组成左上角对齐,右上角对齐,左居中对齐,右居中对齐,左下角对齐,右下角对齐,居中。