1、创建Category(类别)
2、在.m文件中实现顶部对齐和底部对齐的方法
具体代码如下:
// label顶部对齐
- (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底部对齐
- (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文件中声明这两个方法
具体代码如下:
- (void)topAlignment;
- (void)bottomAlignment;
4、在代码中的使用
具体代码如下:
[_descLabel topAlignment];
结语
很简单实用的 UILabel 顶部对齐和底部对齐。
~~ 劝君努力,势必成功! ~~