首页 > 代码库 > iOS Label 自适应高度

iOS Label 自适应高度

推荐第二个

测试一,只改变numberOfLines属性,label的高度不会自适应(会有text中的一部分内容称为......)
    NSString *str = @"jgreijgirjeirgjierjgiu4t9eumctuv5 vtmnvghvmc5v5tgh58tc857y";
    UILabel *label  = [[UILabel alloc]initWithFrame:CGRectMake(50, 50, 100, 100)];
    label.font = [UIFont systemFontOfSize:15];
    label.backgroundColor = [UIColor cyanColor];
    label.numberOfLines = 0;
    label.text = str;
    NSLog(@"label1.frame = %@",NSStringFromCGRect(label.frame));
    [self.view addSubview:label];

    
    测试二,如果加上numberOfLines属性和[label1 sizeToFit]这句话,label的高度会根据你设置的宽度自适应,自己最开始设置的fram的高度会失效,,,注意注意:其实他的宽度和你的设置也有一定的偏差
    UILabel *label1  = [[UILabel alloc]initWithFrame:CGRectMake(100 ,150, 100, 0)];
    label1.font = [UIFont systemFontOfSize:15];
    label1.backgroundColor = [UIColor cyanColor];
    label1.numberOfLines = 0;
    label1.text = str;
    [label1 sizeToFit];
    NSLog(@"label1.frame = %@",NSStringFromCGRect(label1.frame));
    [self.view addSubview:label1];
    
    
    测试三:用老师封装的类(Category)中的方法(autolayoutContent:origin:FontFloat:contentWidth:),不用设置numberOfLines属性和[label1 sizeToFit]方法,,,但设置的contentWidth:宽度和真实的是有一点偏差的
    UILabel *label2  = [[UILabel alloc]initWithFrame:CGRectMake(100 , 300, 100, 0)];
   // label2.font = [UIFont systemFontOfSize:15];
    label2.backgroundColor = [UIColor blueColor];
    label2.text = str;
    [label2 autolayoutContent:str origin:CGPointMake(100, 300) FontFloat:30 contentWidth:150];
    NSLog(@"label2.frame = %@",NSStringFromCGRect(label2.frame));
    [self.view addSubview:label2];
    
    
    测试四:label自适应高度的非主流方法(用到numberOfLines和sizeThatFits:方法),,优点:宽度精准
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(150, 50, 150, 0)];
    label3.font = [UIFont systemFontOfSize:15];
    label3.backgroundColor = [UIColor yellowColor];
    label3.numberOfLines = 0;
    label3.text = str;
    //label3.lineBreakMode = NSLineBreakByWordWrapping;//(默认)
    CGSize size = [label3 sizeThatFits: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.view addSubview:label3];

 

iOS Label 自适应高度