1、創(chuàng)建Category(類(lèi)別)

1.1 選擇iOS下Objective-C File

1.2 選擇UILabel 創(chuàng)建Category

1.3 在對(duì)應(yīng)的位置就是新建的Category
2、在.m文件中實(shí)現(xiàn)頂部對(duì)齊和底部對(duì)齊的方法

2.1 在.m文件中實(shí)現(xiàn)頂部對(duì)齊和底部對(duì)齊的方法
具體代碼如下:
// label頂部對(duì)齊
- (void)topAlignment
{
CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
CGRect rect = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil];
self.numberOfLines = 0;
NSInteger newLinesToPad = (self.frame.size.height - rect.size.height)/size.height;
for (NSInteger i = 0; i < newLinesToPad; i ++) {
self.text = [self.text stringByAppendingString:@"\n "];
}
}
// label底部對(duì)齊
- (void)bottomAlignment
{
CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
CGRect rect = [self.text boundingRectWithSize:CGSizeMake(self.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil];
self.numberOfLines = 0;
NSInteger newLinesToPad = (self.frame.size.height - rect.size.height)/size.height;
for (NSInteger i = 0; i < newLinesToPad; i ++) {
self.text = [NSString stringWithFormat:@" \n%@",self.text];
}
}
3、在.h文件中聲明這兩個(gè)方法

3.1 在.h文件中聲明這兩個(gè)方法
具體代碼如下:
- (void)topAlignment;
- (void)bottomAlignment;
4、在代碼中的使用

4.1 在代碼中的使用
具體代碼如下:
[_descLabel topAlignment];
結(jié)語(yǔ)
很簡(jiǎn)單實(shí)用的 UILabel 頂部對(duì)齊和底部對(duì)齊。
~~ 勸君努力,勢(shì)必成功! ~~