当一段文字需要设置行间距,字号时计算文字高度 分段设置字体颜色
我们在做界面的时候经常会碰到类似计算文字高度的情况,当计算文字高度的同时又需要设置行间距的时候,就会稍微复杂。UILable有一个attributedText的属性,可以用这个来设置相应的字段颜色,行间距,然后计算文字高度。
1 //引入一段文字 2 NSString * str = @"我也刚从这个卖鸡蛋的吧找到正主尔!为柴鸡蛋大大默哀!欢迎大家到隔壁作者柴鸡。我也刚从这个卖鸡蛋的吧找到正主尔!为柴鸡蛋大大默哀!欢迎大家到隔壁作者柴鸡"; 3 4 //初始化 5 NSMutableParagraphStyle * parag = [[NSMutableParagraphStyle alloc]init]; 6 //行间距为3 7 [parag setLineSpacing:3]; 8 9 //文字属性是以字典形式来设置的。 设置行间距为3 字体为12号字 10 NSDictionary * attar = @{NSParagraphStyleAttributeName:parag,NSFontAttributeName:[UIFont systemFontOfSize:12]}; 11 /** 12 计算文字高度的方法 13 parameters: 14 size : 文字的最大范围,宽高都取最大值 15 options : 文字分段模式 16 attribute : 文字的相关约束 17 context : 上下文 18 19 返回的是CGRect 数据 20 */ 21 CGRect rect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) 22 options:NSStringDrawingUsesLineFragmentOrigin 23 attributes:attar 24 context:nil]; 25 26 //用计算出来的宽度 高度来初始化UILable控件 27 UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, rect.size.width, rect.size.height)]; 28 29 //用str来初始化NSMutableAttributedString 30 NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:str]; 31 32 //用UILable 的这个属性设置文字 33 lable.attributedText = string; 34 35 [self.view addSubView:lable];
还一种情况需要分段设置颜色
1 NSString * str = @"我也刚从这个卖鸡蛋的吧找到正主尔!为柴鸡蛋大大默哀!欢迎大家到隔壁作者柴鸡。我也刚从这个卖鸡蛋的吧找到正主尔!为柴鸡蛋大大默哀!欢迎大家到隔壁作者柴鸡"; 2 3 NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:str]; 4 5 NSDictionary * attributed = @{NSForegroundColorAttributeName:[UIColor redColor]}; 6 7 NSRange range = NSMakeRange(0, 5); 8 9 [string setAttributes:attributed range:range]; 10 11 NSDictionary * attibute2 = @{NSForegroundColorAttributeName:[UIColor yellowColor]}; 12 13 NSRange range2 = NSMakeRange(6, 10); 14 15 [string setAttributes:attibute2 range:range2]; 16 17 UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 100, 300, 200)]; 18 19 lable.attributedText = string; 20 21 [self.view addSubView:lable];