我可能在这里遗漏了一些非常微不足道的东西,但我不知道如何获得我的 UILabel 的宽度。请注意,它是以编程方式添加的,并且它的大小适合其中的文本(文本从 2 到 35 个字符不等)。它会自动适应其内容的正确宽度,但我需要获取宽度。
我将它添加到屏幕的代码:
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];
请注意以下代码(带有“Bounds”/“Frame”)始终返回 0.00:
NSLog(@"textlabel width: %f", textLabel.bounds.size.width);
最佳答案
您只能在第一次布局通过后找出尺寸。所以要么等待,要么打电话
[textLabel layoutIfNeeded];
立即布局。之后,应将框架设置为正确的值。
关于ios - 使用 AutoLayout 获取 UILabel 宽度很热门吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20590105/