IOS中label的自适应高度(四种方法)
测试一,只改变numberOfLines属性,label的高度不会自适应(会有text中的一部分内容称为......)
NSString*str =@"jgreijgirjeirgjierjgiu4t9eumctuv5 vtmnvghvmc5v5tgh58tc857y";
UILabel*label = [[UILabelalloc]initWithFrame:CGRectMake(50,50,100,100)];
label.font= [UIFontsystemFontOfSize:15];
label.backgroundColor= [UIColorcyanColor];
label.numberOfLines=0;
label.text= str;
NSLog(@"label1.frame = %@",NSStringFromCGRect(label.frame));
[self.viewaddSubview:label];
测试二,如果加上numberOfLines属性和[label1 sizeToFit]这句话,label的高度会根据你设置的宽度自适应,自己最开始设置的fram的高度会失效,,,注意注意:其实他的宽度和你的设置也有一定的偏差
UILabel*label1 = [[UILabelalloc]initWithFrame:CGRectMake(100,150,100,0)];
label1.font= [UIFontsystemFontOfSize:15];
label1.backgroundColor= [UIColorcyanColor];
label1.numberOfLines=0;
label1.text= str;
[label1sizeToFit];
NSLog(@"label1.frame = %@",NSStringFromCGRect(label1.frame));
[self.viewaddSubview:label1];
测试三:用老师封装的类(Category)中的方法(autolayoutContent:origin:FontFloat:contentWidth:),不用设置numberOfLines属性和[label1 sizeToFit]方法,,,但设置的contentWidth:宽度和真实的是有一点偏差的
UILabel*label2 = [[UILabelalloc]initWithFrame:CGRectMake(100,300,100,0)];
// label2.font = [UIFont systemFontOfSize:15];
label2.backgroundColor= [UIColorblueColor];
label2.text= str;
[label2autolayoutContent:strorigin:CGPointMake(100,300)FontFloat:30contentWidth:150];
NSLog(@"label2.frame = %@",NSStringFromCGRect(label2.frame));
[self.viewaddSubview:label2];
测试四:label自适应高度的非主流方法(用到numberOfLines和sizeThatFits:方法),,优点:宽度精准
UILabel*label3 = [[UILabelalloc]initWithFrame:CGRectMake(150,50,150,0)];
label3.font= [UIFontsystemFontOfSize:15];
label3.backgroundColor= [UIColoryellowColor];
label3.numberOfLines=0;
label3.text= str;
//label3.lineBreakMode = NSLineBreakByWordWrapping;//(默认)
CGSizesize = [label3sizeThatFits:CGSizeMake(label3.frame.size.width,MAXFLOAT)];
label3.frame=CGRectMake(label3.frame.origin.x, label3.frame.origin.y, label3.frame.size.width, size.height);
NSLog(@"label3.frame = %@",NSStringFromCGRect(label3.frame));
[self.viewaddSubview:label3];
上一篇: 企业入云端 别一味纠结安全问题
下一篇: URL合法化