lable自动适配大小

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    UILabel *labelTest = [[UILabel alloc]init];

    labelTest.backgroundColor = [UIColor blackColor];

    labelTest.textColor = [UIColor whiteColor];

    labelTest.font = [UIFont systemFontOfSize:15];

    

    labelTest.layer.borderColor = [UIColor redColor].CGColor;

    labelTest.layer.borderWidth = 1;

    labelTest.text = @"最近一年多,尽管交易数据靓丽,但经过一年操作后,老王发现炒房还是没有利润空间。他终于明白,房价已失去大涨的土壤环境,主要是房源库存量大,传统企业生存艰难,年轻人购房欲望减弱,资产配置转向资本市场,炒房已经到了末日”[2006年至2011年,温州市区商品房销售均价从8045/平方米一路上涨至34674/平方米,5年时间涨了3倍左右。老王说,温州房价每平方米从1万元涨到2万元,花了一年多点时间;从2万元涨到3万元,只用了一年不到。][2009年,温州人均GDP4604美元,在浙江省排倒数第三,不到杭州的一半,也只有浙江省人均GDP71%";

    [labelTest setNumberOfLines:0];

    

    //设置段落风格

    NSMutableParagraphStyle *par = [[NSMutableParagraphStyle alloc]init];

    par.lineHeightMultiple = NSLineBreakByCharWrapping;

    

    //设置段落字体风格

    NSDictionary *dic = @{NSFontAttributeName:labelTest.font,                          NSParagraphStyleAttributeName:par.copy};

    

    //计算 lable 的实际大小  返回文本绘制的区域

    CGRect rect = [labelTest.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width-40, self.view.frame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

    labelTest.frame = CGRectMake(20, 100, rect.size.width, rect.size.height);

    [self.view addSubview:labelTest];

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

原文地址:https://www.cnblogs.com/Mrliheng/p/5434009.html