在工作中,由于label的值大多數(shù)是網(wǎng)絡(luò)獲取的字數(shù)來決定label的高度,所以寫了一個label的分類,如果label的寬高確定,想將label的文字全部顯示,那只能講里面的文字變小,label中有一個屬性能自動實現(xiàn):
label.adjustsFontSizeToFitWidth=YES;
UILabel+Extension.h 文件
-(CGFloat)getSpaceLabelHeight:(NSString *)str withWidh:(CGFloat)width;
UILabel+Extension.m 文件
-(CGFloat)getSpaceLabelHeight:(NSString *)str withWidh:(CGFloat)width
{
NSMutableParagraphStyle *paragphStyle=[[NSMutableParagraphStyle alloc]init];
paragphStyle.lineSpacing=0;//設(shè)置行距為0
paragphStyle.firstLineHeadIndent=0.0;
paragphStyle.hyphenationFactor=0.0;
paragphStyle.paragraphSpacingBefore=0.0;
NSDictionary *dic=@{
NSFontAttributeName:[UIFont systemFontOfSize:15], NSParagraphStyleAttributeName:paragphStyle, NSKernAttributeName:@1.0f
};
CGSize size=[str boundingRectWithSize:CGSizeMake(width, HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil].size;
return size.height;
}
使用的時候?qū)腩^文件使用即可
#import "ViewController.h"
#import "UILabel+Extension.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addLabel];
}
#pragma mark ----addLabel
-(void)addLabel
{
NSString *str=@"adjakdfnafn一生會遇見很多人??傆幸恍┤嗽诤臀覀儞]手說再見。那些給過你歡笑的人,在下一個路口,可能就會成為再也不見的人。那些給過你傷痛的人,在離開的時候,也許就成了一個后會無期。那些給過你美好的人,有一天只能拿來回憶asdfhadsfjadfasf;aksdfnlkasdsdj";
UILabel *label=[UILabel new];
[label setTextColor:[UIColor whiteColor]];
[label setBackgroundColor:[UIColor blackColor]];
[label setText:str];
[label setFont:[UIFont systemFontOfSize:15]];
[label setNumberOfLines:0];
CGFloat h=[label getSpaceLabelHeight:label.text withWidh:300 ];
[label setFrame:CGRectMake(50, 200, 300, h)];
[self.view addSubview:label];
}
@end
Demo:https://github.com/Lee-Z/DynamicAcquisitionLabel.git
效果圖

動態(tài)Label.png