背景:在開發(fā)過程中有一個讓UILabel無論高度多少,讓文字內容始終在頂部。
解決方案:想到的解決方案也有很多,比如:用sizeToFit改變UILabel的高度、尾部強制補齊、UITextField或UITextView來替換UILabel。
對以上方案的分析:覺得以上方案都不是最優(yōu),而且比較粗暴,關鍵擴展性不高比較局限,只滿足了文字內容在頂部。如果需求更改為底部對齊呢?
最優(yōu)方案:重寫UILabel的drawInRect方法
.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface WlcLable : UILabel
@end
NS_ASSUME_NONNULL_END
.m文件
#import "WlcLable.h"
@implementation WlcLable
- (id)initWithFrame:(CGRect)frame {
return [super initWithFrame:frame];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines {
CGRect textRect = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
//重寫CGRect,根據(jù)自己的需求自由發(fā)揮
//頂部對齊
textRect.origin.y = bounds.origin.y;
//頂部左邊距
textRect.origin.x = 10;
textRect.size.width = self.frame.size.width - 10*2;
return textRect;
}
-(void)drawTextInRect:(CGRect)requestedRect {
CGRect actualRect = [self textRectForBounds:requestedRect limitedToNumberOfLines:self.numberOfLines];
[super drawTextInRect:actualRect];
}
@end
方法調用
WlcLable *label = [[WlcLable alloc] init];
label.frame = CGRectMake(10, 100, 300, 300);
label.text = @"頂部對齊,左邊留白10像素";
label.numberOfLines = 0;
label.backgroundColor = [UIColor redColor];
[self.view addSubview:label];
運行結果:

Simulator Screen Shot - iPhone SE (2nd generation) - 2020-08-12 at 14.54.49.png