根据字体多少使UILabel自动调节尺寸

在大多数情况下,给UILabel进行动态数据绑定的时候,往往需要根据字符串的多少,动态调整UILabel的宽度或高度。

 1、UILabel宽度不变,根据字体多少,自动调整UILabel的高度,并折行显示。

代码如下:

    UILabel *lrcLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 200, 50)];
    lrcLabel.font = [UIFont boldSystemFontOfSize:20.0f];  //UILabel的字体大小
    lrcLabel.numberOfLines = 0;  //必须定义这个属性,否则UILabel不会换行
    lrcLabel.textColor = [UIColor whiteColor]; 
    lrcLabel.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [lrcLabel setBackgroundColor:[UIColor greenColor]];
//宽度不变,根据字的多少计算label的高度
    NSString *lrcStr = @"可以更改此内容进行测试,宽度不变,高度根据内容自动调节";
    CGSize size = [lrcStr sizeWithFont:label.font constrainedToSize:CGSizeMake(lrcLabel.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
    //根据计算结果重新设置UILabel的尺寸
    [lrcLabel setFrame:CGRectMake(0, 10, 200, size.height)];
    lrcLabel.text = lrcStr;
    
    [self.view addSubview:lrcLabel];

 

2、UILabel高度不变,根据字体多少,自动调整UILabel的宽度,并折行显示 

 UILabel *lrcLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 200, 50)];
    lrcLabel.font = [UIFont boldSystemFontOfSize:20.0f];  //UILabel的字体大小
    lrcLabel.numberOfLines = 0;  //必须定义这个属性,否则UILabel不会换行
    lrcLabel.textColor = [UIColor whiteColor]; 
    lrcLabel.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    [lrcLabel setBackgroundColor:[UIColor greenColor]];
    
    //高度固定不折行,根据字的多少计算label的宽度
    NSString *lrcStr = @"高度不变获取宽度,获取字符串不折行单行显示时所需要的长度";
    CGSize size = [lrcStr sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, lrcLabel.frame.size.height)];
    NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
    //根据计算结果重新设置UILabel的尺寸
    [label setFrame:CGRectMake(0, 10, size.width, 20)];
    lrcLabel.text = lrcStr;
    
    [self.view addSubview:lrcLabel];

 

posted @ 2015-04-28 20:50  apple家园  阅读(268)  评论(0编辑  收藏  举报