我们平时在写label时候,如果遇到换行会设置numberOfLines = 0;这样就会自动换行,这个时候,会有一个问题,如果字数一行能显示完,那么label里面的文字就会呈现出上下居中对齐,这个时候单行显示内容和多行显示内容如果在一起排列的话就很不美观,我们心里想的方案其实就是,无论label是单行显示还是多行显示,label里的文字要和label顶部对齐,也就是所谓的吸顶状态。如下图
如何设置呢,方法也比较多,今天给出一个方法,也就是重写label的drawInRect方法
新建一个label继承于UILabel
接下来是重点也就是重写drawInRect方法
- (instancetype)init
{
self = [super init];
return self;
}
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
textRect.origin.y = bounds.origin.y;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}