一. IOS7之后版本
tableview的cell需要根据文字内容的长度计算不同文字行数的不同高度,从而动态调整cell的高度,因此需要根据文字的长度和cell的固定宽度来计算文字段落有多少行,高度为多少,实现这个的函数为NSString的boundingRectWithSize函数,这个函数适用于IOS7以后版本中:
//
// LabelHeightViewController.m
// JXHDemo
//
// Created by919575700@qq.com on 10/21/15.
// Copyright (c)2015 Jiangxh. All rights reserved.
//
#define labelW 300//label的固定宽度
#define fontSize 20//字体大小
#define lingSpace 5//行间距
#import"LabelHeightViewController.h"
@implementationLabelHeightViewController
- (void)viewDidLoad{
[superviewDidLoad];
self.view.backgroundColor=RGBColor(230,230,230);
NSString*text =@"秋叶黄,秋叶黄,我深深的沉醉其中,摇摆的叶片,枯黄着也是秋天,飘落着也是秋天;秋叶黄,秋叶黄,你随风悄悄的散去,枯萎的树枝,下着雨也是秋天,吹着风也是秋天.";
//就用这两个options枚举参数吧,我也不知道为啥
NSStringDrawingOptionsoptions= NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading;
// labelW是段落的固定宽度;CGFLOAT_MAX固定用这个;attributes按照下面的语句fontSize是字体的大小
// >IOS7
CGFloatlabelH= [text boundingRectWithSize:CGSizeMake(labelW,CGFLOAT_MAX)options:optionsattributes:@{NSFontAttributeName:[UIFontsystemFontOfSize:fontSize]}context:nil].size.height;
//
//CGFloat labelH = [textsizeWithFont:[UIFont systemFontOfSize:fontSize]constrainedToSize:CGSizeMake(labelW,CGFLOAT_MAX)].height;
//打印计算的高度看一下
NSLog(@"文字段落高度为:%f",labelH);
//实际行数
NSIntegerlineNum = labelH/fontSize;
NSMutableParagraphStyle*paragraphStyle= [[ NSMutableParagraphStyle alloc]init];
//文字对齐方式
paragraphStyle.alignment=NSTextAlignmentJustified;
//段落首字符缩进两个字
paragraphStyle.firstLineHeadIndent=2*fontSize;
//每行行首缩进
paragraphStyle.headIndent=10;
//行间距
paragraphStyle.lineSpacing=lingSpace;
//属性字典,包括前景字体颜色和段落属性
NSDictionary*attributes= @{NSForegroundColorAttributeName:[UIColorredColor],NSParagraphStyleAttributeName:paragraphStyle};
//属性字符串
NSAttributedString*attributedText= [[ NSAttributedString alloc ]initWithString :text attributes :attributes];
UILabel*label1 = [[UILabelalloc]initWithFrame:CGRectMake(0,70,300,labelH+lineNum*lingSpace)];
//文字行数设置为0
label1.numberOfLines=0;
// label背景色
label1.backgroundColor=[UIColor greenColor];
label1.attributedText= attributedText;
//显示label
[self.viewaddSubview:label1];
}
@end
二. 在IOS7之前的版本,高度的计算用下面的函数:
CGFloat labelH =[text sizeWithFont:[UIFont systemFontOfSize:fontSize]constrainedToSize:CGSizeMake(labelW,CGFLOAT_MAX)].height;
三. 一般情况下工程里直接把上面两种情况封装在NSString类的拓展里面,方便用简单参数直接调用:
#import"NSString+Extension.h"
@implementationNSString (Extension)
#pragma clang diagnosticpush
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
- (CGSize)sizeWithFont:(UIFont*)font maxW:(CGFloat)maxW
{
NSMutableDictionary*attrs= [NSMutableDictionary dictionary];
attrs[NSFontAttributeName]= font;
CGSizemaxSize = CGSizeMake(maxW,MAXFLOAT);
//获得系统版本
if(iOS7){
NSStringDrawingOptionsoptions= NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading;
return[selfboundingRectWithSize:maxSizeoptions:optionsattributes:attrscontext:nil].size;
} else{
return[selfsizeWithFont:fontconstrainedToSize:maxSize];
}
}
- (CGSize)sizeWithFont:(UIFont*)font
{
return[selfsizeWithFont:fontmaxW:MAXFLOAT];
}
@end