您的位置:首页 > 产品设计 > UI/UE

iOS经典讲解之UILabel居上居下显示

2016-05-12 10:16 579 查看
作者:刘新林

转载请标明出处:http://blog.csdn.net/loving_ios/article/details/51381778

在日常开发中,经常遇到UILabel内容显示问题,因为UILabel没有提供居上居下显示的方法,给开发带来了诸多不便,下面提供一种ULabel居上居下显示的方法仅供参考(通过类目实现)。

#import <UIKit/UIKit.h>

@interface UILabel (Vertical)
// align top
- (void)alignTop;
// align bottom
- (void)alignBottom;
@end
#import "UILabel+Vertical.h"

@implementation UILabel (Vertical)
-(void)alignTop
{
// 对应字号的字体一行显示所占宽高
CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
// 多行所占 height*line
double height = fontSize.height*self.numberOfLines;
// 显示范围实际宽度
double width = self.frame.size.width;
// 对应字号的内容实际所占范围
CGSize stringSize = [self.text boundingRectWithSize:CGSizeMake(width, height) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:self.font} context:nil].size;
// 剩余空行
NSInteger line = (height - stringSize.height) / fontSize.height;
// 用回车补齐
for (int i = 0; i < line; i++) {

self.text = [self.text stringByAppendingString:@"\n "];
}
}
-(void)alignBottom
{
CGSize fontSize = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}];
double height = fontSize.height*self.numberOfLines;
double width = self.frame.size.width;
CGSize stringSize = [self.text boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.font} context:nil].size;

NSInteger line = (height - stringSize.height) / fontSize.height;
// 前面补齐换行符
for (int i = 0; i < line; i++) {
self.text = [NSString stringWithFormat:@" \n%@", self.text];
}
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: