2013-12-15 63 views
0

我可能在这里错过了一些很琐碎的事情,但我无法弄清楚如何获得我的UILabel的宽度。请注意,它是以编程方式添加的,并且它的大小与它内部的文本相符(文本从2到35个字符不等)。它自动适合其内容的正确宽度,但我需要获得宽度。热点使用AutoLayout获取UILabel宽度?

我的代码,将其添加到屏幕上:

UILabel *textLabel = [[UILabel alloc] init]; 
    textLabel.text = textInputFromUser; 
    textLabel.textColor = [UIColor whiteColor]; 
    textLabel.backgroundColor = [UIColor colorWithRed:40.0/255.0 green:40.0/255.0 blue:40.0/255.0 alpha:0.95]; 
    textLabel.translatesAutoresizingMaskIntoConstraints = NO; 
    [self.view addSubview:textLabel]; 

注意,下面的代码(以 “边界”/ “框架”)总是返回0.00):

NSLog(@"textlabel width: %f", textLabel.bounds.size.width); 
+0

你试过'textLabel.frame.size.width'吗? – CaptJak

+0

是的,看第二个代码片段 – anthoprotic

回答

3

只能找出第一个布局通液之后的大小。所以要么等待,要么致电

[textLabel layoutIfNeeded]; 

立即进行布局。之后,框架应设置为正确的值。

+0

谢谢,它的工程太棒了!更好的方式,我的自定义黑客大声笑。 – anthoprotic

0

既然没有人其他答案,我会投入我的两分钱...

我假设你无法获得标签的框架的原因是因为框架还没有技术上被实例化;但是,也许只是获得内容的大小就足以满足您的需求。

这里有一个文章,解释了如何使用boundingRectWithSize:选项:属性:背景:让你的标签的文字大小:https://stackoverflow.com/a/18961502/2274694

+0

我不能工作。我想我会根据我的UILabel中有多少个字符进行计算。不是最优的,但可能工作 – anthoprotic

0

尝试用假帧像这样初始化标签:

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1,1)]; 
textLabel.text = textInputFromUser; 
[textLabel sizeToFit]; 

,或者你可以尝试:

UILabel *textLabel = [[UILabel alloc] initWithString:textInputFromUser]; 
+0

不幸的是,它仍然返回0.00作为框架的宽度 – anthoprotic