.h中
//****************************************************************************************************************************************************************************************
#import <UIKit/UIKit.h>
@interface UILabel (LabelHeightAndWidth)
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString *)title font:(UIFont*)font;
+ (CGFloat)getWidthWithTitle:(NSString *)title font:(UIFont *)font;
@end
.m 中
//****************************************************************************************************************************************************************************************
#import "UILabel+LabelHeightAndWidth.h"
@implementation UILabel (LabelHeightAndWidth)
+ (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
本文介绍了一个用于 iOS 开发的自定义 UILabel 类方法,通过该方法可以计算 UILabel 的高度和宽度,使其能够根据文本内容自动调整大小。适用于需要 UILabel 动态调整尺寸以适应不同文本长度的场景。
4760

被折叠的 条评论
为什么被折叠?



