1. 创建UILable 的 category
.h中+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString*)title font:(UIFont*)font;+ (CGFloat)getWidthWithTitle:(NSString*)title font:(UIFont*)font;
.m中
+ (CGFloat)getHeightByWidth:(CGFloat)width title:(NSString*)title font:(UIFont*)font{
UILabel*label = [[UILabelalloc] initWithFrame:CGRectMake(0,0, width,0)];
label.text = title; label.font = font;
label.numberOfLines =0; [label sizeToFit];
CGFloatheight = label.frame.size.height;returnheight;
}
+ (CGFloat)getWidthWithTitle:(NSString*)title font:(UIFont*)font {
UILabel*label = [[UILabelalloc] initWithFrame:CGRectMake(0,0,1000,0)];
label.text = title;
label.font = font;
[label sizeToFit];
returnlabel.frame.size.width;
}
2. 使用时 引入头文件
#import"UILabel+LabelHeightAndWidth.h"
#pragma mark - labelOne SizeToFitHeight
- (void)buildLabelOne{
UILabel*labelOne = [[UILabelalloc] initWithFrame:CGRectMake(10,30,200,50)];
labelOne.text =@"这是labelOne的高度自适应这是labelOne的高度自适应这是labelOne的高度自适应这是labelOne的高度自适应"; labelOne.backgroundColor = [UIColorgrayColor];
labelOne.font = [UIFontsystemFontOfSize:20];
labelOne.numberOfLines =0;
CGFloatheight = [UILabelgetHeightByWidth:labelOne.frame.size.width title:labelOne.text font:labelOne.font];
labelOne.frame =CGRectMake(10,30,200, height); [self.view addSubview:labelOne]; }
#pragma mark - labelTwo SizeToFitWidth
- (void)buildLabelTwo{
UILabel*labelTwo = [[UILabelalloc] initWithFrame:CGRectMake(10,300,50,100)];
labelTwo.text =@"这是labelTwo的宽度自适应这是labelTwo的宽度自适应这是labelTwo的宽度自适应";
labelTwo.backgroundColor = [UIColor cyanColor];
labelTwo.font = [UIFontsystemFontOfSize:20];
CGFloatwidth = [UILabelgetWidthWithTitle:labelTwo.text font:labelTwo.font];
labelTwo.frame =CGRectMake(10,300, width,100);
[self.view addSubview:labelTwo];
}
网友评论