1 创建category
.h文件
#import <UIKit/UIKit.h>
@interface UILabel (HCL)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
.m文件
#import "UILabel+HCL.h"
@implementation UILabel (HCL)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
label.text = title;
label.font = font;
label.numberOfLines = 0;
[label sizeToFit];
CGFloat height = label.frame.size.height;
return height;
}
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 1000, 0)];
label.text = title;
label.font = font;
[label sizeToFit];
return label.frame.size.width;
}
@end
使用方法:
//文字label
UILabel* bodyLabel = [[UILabel alloc]initWithFrame: CGRectMake(2, 60, self.frame.size.width, 20)];
bodyLabel.text = dic[@"text"];
NSLog(@"%@",dic[@"text"]);
bodyLabel.numberOfLines = 0;
bodyLabel.font = [UIFont systemFontOfSize:14];
CGFloat hight = [UILabel getHeightByWidth:bodyLabel.frame.size.width title:bodyLabel.text font:bodyLabel.font];
//适应宽度
// CGFloat width = [UILabel getWidthWithTitle:bodyLabel.text font:bodyLabel.font];
//bodyLabel.frame = CGRectMake(2, 60, width, 100);
bodyLabel.frame = CGRectMake(2, 60, self.frame.size.width, hight);
[self addSubview:bodyLabel];