我可能在这里错过了一些很琐碎的事情,但我无法弄清楚如何获得我的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