我可能在這裏錯過了一些很瑣碎的事情,但我無法弄清楚如何獲得我的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);
你試過'textLabel.frame.size.width'嗎? – CaptJak
是的,看第二個代碼片段 – anthoprotic