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

来源:互联网 发布:mysql忘记密码 编辑:程序博客网 时间:2024/05/16 09:33
////  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 0
原创粉丝点击