1. 創(chuàng)建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. 使用時(shí) 引入頭文件
#import"UILabel+LabelHeightAndWidth.h"
#pragma mark - labelOne SizeToFitHeight
- (void)buildLabelOne{
UILabel*labelOne = [[UILabelalloc] initWithFrame:CGRectMake(10,30,200,50)];
labelOne.text =@"這是labelOne的高度自適應(yīng)這是labelOne的高度自適應(yīng)這是labelOne的高度自適應(yīng)這是labelOne的高度自適應(yīng)"; 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的寬度自適應(yīng)這是labelTwo的寬度自適應(yīng)這是labelTwo的寬度自適應(yīng)";
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];
}