2013-12-15 62 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