• iOS常用技术-计算Label高度


     1 //
     2 //  ViewController.m
     3 //  计算Label高度
     4 //
     5 //  Created by 大欢 on 16/1/19.
     6 //  Copyright © 2016年 bjsxt. All rights reserved.
     7 //
     8 
     9 #import "ViewController.h"
    10 
    11 @interface ViewController ()
    12 
    13 @end
    14 
    15 @implementation ViewController
    16 
    17 - (void)viewDidLoad {
    18     [super viewDidLoad];
    19 
    20 //    [self example1];
    21     
    22     //多行文本计算高度
    23     
    24     CGFloat width = self.view.frame.size.width - 40;
    25     
    26     NSString * string = @"还记得你说家是唯一的城堡随着稻香河流继续奔跑微微笑 小时候的梦我知道不要哭让萤火虫带著你逃跑乡间的歌谣永远的依靠回家吧 回到最初的美好 ";
    27     
    28     NSMutableParagraphStyle * paragraph = [[NSMutableParagraphStyle alloc] init];
    29     paragraph.lineSpacing = 10;
    30     
    31     NSDictionary * dict = @{NSFontAttributeName:[UIFont systemFontOfSize:30],
    32                             NSParagraphStyleAttributeName:paragraph};
    33     
    34     NSAttributedString * attribute = [[NSAttributedString alloc]
    35                                       initWithString:string attributes:dict];
    36     //一定要先确定宽度,再根据宽度和字体计算size
    37     CGSize size = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    38     
    39     UILabel * label = [[UILabel alloc] init];
    40     label.bounds = CGRectMake(0, 0, size.width, size.height);
    41     label.center = self.view.center;
    42     label.numberOfLines = 0;
    43     label.attributedText = attribute;
    44     label.backgroundColor = [UIColor yellowColor];
    45     [self.view addSubview:label];
    46     
    47 }
    48 
    49 - (void)example1 {
    50     //获取一行label的size
    51     
    52     NSString * string = @"黑猫警长";
    53     NSDictionary * dict = @{NSFontAttributeName:[UIFont systemFontOfSize:50]};
    54     CGSize size = [string sizeWithAttributes:dict];
    55     
    56     UILabel * label = [[UILabel alloc] init];
    57     label.text = string;
    58     label.bounds = CGRectMake(0, 0, size.width, size.height);
    59     label.center = self.view.center;
    60     label.font = [UIFont systemFontOfSize:50];
    61     label.backgroundColor = [UIColor orangeColor];
    62     [self.view addSubview:label];
    63 }
    64 @end


  • 相关阅读:
    bzoj2815: [ZJOI2012]灾难
    bzoj1188: [HNOI2007]分裂游戏
    bzoj4538: [Hnoi2016]网络
    bzoj3594: [Scoi2014]方伯伯的玉米田
    bzoj2595: [Wc2008]游览计划
    bzoj3277: 串
    Django开发:(3.2)ORM:多表操作
    Django开发:(3.1)ORM:单表操作
    Django:(2)视图层&模板层
    Django开发:(1)django基础 & url控制器
  • 原文地址:https://www.cnblogs.com/MrWuYindi/p/5146580.html
Copyright © 2020-2023  润新知