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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Loving_iOS/article/details/51381778

作者:刘新林

转载请标明出处: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



猜你喜欢

转载自blog.csdn.net/Loving_iOS/article/details/51381778