#import <UIKit/UIKit.h> @interface UILabel (UILabel_LabelHeighAndWidth)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font; + (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
#import "UILabel+UILabel_LabelHeighAndWidth.h" @implementation UILabel (UILabel_LabelHeighAndWidth)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont *)font // 自适应高
{ UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , width, )];
label.text = title;
label.font = font;
label.numberOfLines = ;
[label sizeToFit];
CGFloat height = label.frame.size.height;
return height;
} + (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font {// 自适应宽
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(, , , )];
label.text = title;
label.font = font;
[label sizeToFit];
return label.frame.size.width;
}
@end
例如:CGFloat width1 = [UILabel getWidthWithTitle:strzhengcahngshu font:cell.zhengchangLabel.font];
cell.zhengchangshuLabel.frame = CGRectMake(46, 60, width1, 15);
cell.zhengchangshuLabel.text = strzhengcahngshu;
说明:记得引入头文件
#import "UILabel+UILabel_LabelHeighAndWidth.h"