原文:http://blog.csdn.net/enuola/article/details/8559588app
在大多属性状况下,给UILabel进行动态数据绑定的时候,每每须要根据字符串的多少,动态调整UILabel的宽度或高度。oop
下面分两种状况考虑:测试
一、UILabel宽度不变,根据字体多少,自动调整UILabel的高度,并折行显示。字体
代码以下:spa
- UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 20)];
- label.font = [UIFont boldSystemFontOfSize:20.0f];
- label.numberOfLines = 0;
- label.textColor = [UIColor whiteColor];
- label.textAlignment = NSTextAlignmentLeft;
- [label setBackgroundColor:[UIColor redColor]];
-
-
- NSString *str = @"能够更改此内容进行测试,宽度不变,高度根据内容自动调节";
- CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
-
- [label setFrame:CGRectMake(0, 10, 200, size.height)];
- label.text = str;
-
- [self.view addSubview:label];
- [label release];
二、UILabel高度不变,根据字体多少,自动调整UILabel的宽度,并折行显示
代码以下:.net
- UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
- label.font = [UIFont boldSystemFontOfSize:20.0f];
- label.numberOfLines = 0;
- label.textColor = [UIColor whiteColor];
- label.textAlignment = NSTextAlignmentLeft;
- [label setBackgroundColor:[UIColor redColor]];
-
-
- NSString *str = @"高度不变获取宽度,获取字符串不折行单行显示时所须要的长度";
- CGSize size = [str sizeWithFont:label.font constrainedToSize:CGSizeMake(MAXFLOAT, label.frame.size.height)];
- NSLog(@"size.width=%f, size.height=%f", size.width, size.height);
-
- [label setFrame:CGRectMake(0, 10, size.width, 20)];
- label.text = str;
-
- [self.view addSubview:label];
- [label release];
其中两种状况,核心代码均为size处的代码,均要把对应的size设置为MAXFLOAT