下面代码示范了如何自动计算UILabel尺寸以适应文本的展示:
NSString * myText = [NSString stringWithString:@"some text"];
//获取到文本大大小
CGFloat constrainedSize = 265.0f; //其他大小也行
UIFont * myFont = [UIFont fontWithName:@"Arial" size:19]; // UILabel使用的字体
CGSize textSize = [myText sizeWithFont: myFont
constrainedToSize:CGSizeMake(constrainedSize, CGFLOAT_MAX)
lineBreakMode:UILineBreakModeWordWrap];
//床架UILabel
CGRect labelFrame = CGRectMake (0, 0, textSize.width, textSize.height);
UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
[label setFont:myFont];
[label setText:myText];
[self addSubview:label];
...
[label release];