???????系統中的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,可以組成左上角對齊,右上角對齊,左居中對齊,右居中對齊,左下角對齊,右下角對齊,居中。