动态计算UILabel的高度,宽度,自动换行

//
//  ViewController.m
//  Company_Code_动态计算字体高度和宽度
//
//  Created by 麦子 on 15/8/17.
//  Copyright (c) 2015年 麦子. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //进行动态获取高度和宽度。必须用这个NSDictionary,不能用NSMutableDictionary这个。怪
    
    // 单行
    NSString *str            = @"自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行,自动计算高度,然后换行";
    UIFont *font             = [UIFont systemFontOfSize:10.0f];
    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:10.0f] };
    CGSize size              = [str sizeWithAttributes:attributes];

    NSLog(@"宽度:%f,高度:%f",size.width,size.height);

    UILabel *label           = [[UILabel alloc] init];
    label.frame              = CGRectMake(20, 200, size.width, size.height);
    label.text               = str;
    label.font               = font;
    label.backgroundColor    = [UIColor orangeColor];
    [self.view addSubview:label];

    // 自动计算高度,然后换行
    label.lineBreakMode      = NSLineBreakByWordWrapping;
    label.numberOfLines      = 0;
    // 旧版本
//    CGSize brSize = [str sizeWithFont:font constrainedToSize:CGSizeMake([UIScreen mainScreen].bounds.size.width-60, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];

    CGSize boundSize         = CGSizeMake([UIScreen mainScreen].bounds.size.width-100, MAXFLOAT);
    CGSize  brSize           = [str boundingRectWithSize:boundSize options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;

    label.frame              = CGRectMake(20, 200, brSize.width, brSize.height);
    NSLog(@"宽度:%f,高度:%f",brSize.width,brSize.height);
    
    
//    NSStringDrawingTruncatesLastVisibleLine
//    
//    如果文本内容超出指定的矩形限制,文本将被截去并在最后一个字符后加上省略号。如果指定了NSStringDrawingUsesLineFragmentOrigin选项,则该选项被忽略。
//    
//    NSStringDrawingUsesLineFragmentOrigin
//    
//    绘制文本时使用 line fragement origin 而不是 baseline origin。
//    
//    Theorigin specified when drawing the string is the line fragment origin and notthe baseline origin.
//    
//    NSStringDrawingUsesFontLeading
//    
//    计算行高时使用行间距。(译者注:字体大小+行间距=行高)
//    
//    NSStringDrawingUsesDeviceMetrics
//    
//    计算布局时使用图元字形(而不是印刷字体)。

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值