IOS 获取动态Label的高度

在工作中,由于label的值大多数是网络获取的字数来决定label的高度,所以写了一个label的分类,如果label的宽高确定,想将label的文字全部显示,那只能讲里面的文字变小,label中有一个属性能自动实现:

label.adjustsFontSizeToFitWidth=YES;

UILabel+Extension.h 文件

-(CGFloat)getSpaceLabelHeight:(NSString *)str withWidh:(CGFloat)width;

UILabel+Extension.m 文件

-(CGFloat)getSpaceLabelHeight:(NSString *)str withWidh:(CGFloat)width
{

    NSMutableParagraphStyle *paragphStyle=[[NSMutableParagraphStyle alloc]init];
    
    paragphStyle.lineSpacing=0;//设置行距为0
    paragphStyle.firstLineHeadIndent=0.0;
    paragphStyle.hyphenationFactor=0.0;
    paragphStyle.paragraphSpacingBefore=0.0;
    
    NSDictionary *dic=@{
                        
                    NSFontAttributeName:[UIFont systemFontOfSize:15], NSParagraphStyleAttributeName:paragphStyle, NSKernAttributeName:@1.0f
                       
                    };
    CGSize size=[str boundingRectWithSize:CGSizeMake(width, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
    
    return size.height;

}

使用的时候导入头文件使用即可

#import "ViewController.h"
#import "UILabel+Extension.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addLabel];
}

#pragma mark ----addLabel

-(void)addLabel
{
    
    NSString *str=@"adjakdfnafn一生会遇见很多人。总有一些人在和我们挥手说再见。那些给过你欢笑的人,在下一个路口,可能就会成为再也不见的人。那些给过你伤痛的人,在离开的时候,也许就成了一个后会无期。那些给过你美好的人,有一天只能拿来回忆asdfhadsfjadfasf;aksdfnlkasdsdj";
    
    UILabel *label=[UILabel new];
    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor blackColor]];
    [label setText:str];
    [label setFont:[UIFont systemFontOfSize:15]];
    [label setNumberOfLines:0];
    
    CGFloat h=[label getSpaceLabelHeight:label.text withWidh:300 ];
    [label setFrame:CGRectMake(50, 200, 300, h)];
    [self.view addSubview:label];
    
}

@end

Demo:https://github.com/Lee-Z/DynamicAcquisitionLabel.git
效果图

IOS 获取动态Label的高度_第1张图片
动态Label.png

你可能感兴趣的:(IOS 获取动态Label的高度)