根据文字调整UILabel的大小

时间:2014-08-23 23:53:55

标签: objective-c

我想根据UILabel文本调整UILabel的大小。我的代码没有 UILabel根据其宽度..

我目前的代码:

UILabel *textLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(20, 158, self.view.bounds.size.width-40, 550)];
textLabel2.text = textString;
textLabel2.font = [UIFont fontWithName:@"Helvetica Neue" size:17];
textLabel2.numberOfLines = 0;
[textLabel2 sizeToFit];
[self.scroller addSubview:textLabel2];

我该怎么做?

1 个答案:

答案 0 :(得分:0)

有这样的事情吗?

UILabel *label = [[UILabel alloc] init];
//set label backgroundColor so you can see the label width changes according to text
[label setBackgroundColor:[UIColor redColor]];
//edit you label text
[label setText:@"very longgggg text"];

//get width of you text and set you font size to 17.0
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:17.0f]].width;

//set you label frame
label.frame = CGRectMake(10, 200, width, 30);

//add label to you view
[self.view addSubview:label];