根据内容计算宽度
- (CGFloat)calculateRowWidth:(NSString *)string { NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]}; //指定字号 CGRect rect = [string boundingRectWithSize:CGSizeMake(0, 30)/*计算宽度时要确定高度*/ options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil]; return rect.size.width; }
根据内容计算高度
- (CGFloat)calculateRowHeight:(NSString *)string fontSize:(NSInteger)fontSize{ NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};//指定字号 CGRect rect = [string boundingRectWithSize:CGSizeMake(self.view.width - 30, 0)/*计算高度要先指定宽度*/ options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil]; return rect.size.height; }
二、如果两行或者多行 字符串的时候 设置行间隔 在动态计算高度 如下两段代码
- (CGFloat)calculateRowHeight:(NSString *)string fontSize:(NSInteger)fontSize strWithWidthX:(CGFloat)widthX { NSDictionary *dic = [self setParameterWithfloat:5 fontSize:fontSize]; // 计算高度要先指定宽度 CGRect rect = [string boundingRectWithSize:CGSizeMake(kUIScreenWidth - widthX, 0) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:dic context:nil]; return rect.size.height; } //设置行间距 - (NSDictionary *)setParameterWithfloat:(CGFloat )heightForLineSpacing fontSize:(NSInteger)fontSize { NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init]; paraStyle.lineBreakMode = NSLineBreakByCharWrapping; paraStyle.alignment = NSTextAlignmentLeft; // 设置行间距 paraStyle.lineSpacing = heightForLineSpacing; // 指定字号 NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName:paraStyle}; return dic; }