码迷,mamicode.com
首页 > 移动开发 > 详细

iOS常用技术-计算Label高度

时间:2016-01-20 22:29:20      阅读:1596      评论:0      收藏:0      [点我收藏+]

标签:

//
//  ViewController.m
//  计算Label高度
//
//  Created by 大欢 on 16/1/19.
//  Copyright © 2016年 bjsxt. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

//    [self example1];
    
    //多行文本计算高度
    
    CGFloat width = self.view.frame.size.width - 40;
    
    NSString * string = @"还记得你说家是唯一的城堡随着稻香河流继续奔跑微微笑 小时候的梦我知道不要哭让萤火虫带著你逃跑乡间的歌谣永远的依靠回家吧 回到最初的美好 ";
    
    NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineSpacing = 10;
    
    NSDictionary * dict = @{NSFontAttributeName:[UIFont systemFontOfSize:30],
                            NSParagraphStyleAttributeName:paragraph};
    
    NSAttributedString * attribute = [[NSAttributedString alloc]
                                      initWithString:string attributes:dict];
    //一定要先确定宽度,再根据宽度和字体计算size
    CGSize size = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    
    UILabel * label = [[UILabel alloc] init];
    label.bounds = CGRectMake(0, 0, size.width, size.height);
    label.center = self.view.center;
    label.numberOfLines = 0;
    label.attributedText = attribute;
    label.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:label];
    
}

- (void)example1 {
    //获取一行label的size
    
    NSString * string = @"黑猫警长";
    NSDictionary * dict = @{NSFontAttributeName:[UIFont systemFontOfSize:50]};
    CGSize size = [string sizeWithAttributes:dict];
    
    UILabel * label = [[UILabel alloc] init];
    label.text = string;
    label.bounds = CGRectMake(0, 0, size.width, size.height);
    label.center = self.view.center;
    label.font = [UIFont systemFontOfSize:50];
    label.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:label];
}
@end
技术分享

iOS常用技术-计算Label高度

标签:

原文地址:http://www.cnblogs.com/MrWuYindi/p/5146580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!