#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(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
例如: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"
时间: 2024-11-25 11:56:40