Label自适应高度

一:Label自适应高度
     Label自适应一般情况下都会加到UIScrollView上,否则如果文字内容过多,不能完全显示。UITabelView自适应和Label差不多,用到的时候自己体会。
二:代码示例
#import "ViewController.h"

#define WIDTH      [UIScreen mainScreen].bounds.size.width
#define HEIGHT     [UIScreen mainScreen].bounds.size.height

@interface ViewController ()
@end
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
    self.navigationItem.title = @"UITabel常用属性与实现自适应";
    self.view.backgroundColor = [UIColor whiteColor];
   
    UIScrollView * scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    scroll.contentSize = CGSizeMake(0, HEIGHT+100);
    [self.view addSubview:scroll];

//1.创建并初始化UILabel
    UILabel * label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor whiteColor];
    [scroll addSubview:label];
   
//2.设置属性
    label.textColor = [UIColor blackColor];
    label.font = [UIFont systemFontOfSize:15];
    label.numberOfLines = 0;
   
//3.实现UILabel的自适应高度
    //a.获取text属性文本
    label.text = @"        每个人都有各自不同的选择,简单直白地讲,正是因为那些遗憾才成全了现在的自己,任何一种生活方式都没有对错之分,我们要做的不过是认可每一次选择之后,重新来过的自己。(文/荼蘼)";
    //b.计算CGRect,CGSize,设置UILabel的frame,并更新
    CGRect labelFrame = CGRectZero;
    labelFrame.origin = CGPointMake(0, 0);//label的坐标
   
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName,nil];
    CGSize  actualsize =[label.text boundingRectWithSize:CGSizeMake(WIDTH, 10000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading  attributes:tdic context:nil].size;
    labelFrame.size.width = WIDTH;
    labelFrame.size.height = actualsize.height;
    label.frame = labelFrame;//更新UILabel的frame
}

posted on 2015-12-20 16:56  我是神经一把刀  阅读(428)  评论(0编辑  收藏  举报

导航