2015-05-27 58 views
11

我得到一个UILabel [文本已定后]的宽度与:如何在设置文本后获得UILabel的正确宽度?

myUILabel.frame.width 

但它始终是相同的宽度,如果它认为无论字符串:"Hello."或字符串:"Hello everyone on this planet."。但是UILabel需要使用第二个字符串来获得更大的宽度。

+0

使用[myUILabel sizeToFit];我们也可以使用像http://stackoverflow.com/questions/1340667/pixel-width-of-the-text-in-a-uilabel – Venkat

+0

计算宽度为什么你需要宽度?你在使用自动布局吗?如果您使用自动布局,则可以通过播放具有优先级的内容来摆脱它,以便frame.width将返回正确的值 –

+0

您可以查看与自动布局和布局约束有关的标签的内在内容大小。只要谷歌它,也许你甚至实际上想要使用自动布局,当你想知道标签的宽度。 – borchero

回答

26

尝试myUILabel.intrinsicContentSize()。当然,确保先设置字体。

0

您应该使用[label sizeToFit]

sizeToFit标签上会伸展标签以容纳文本。

另一种解决方案是计算字符串的宽度并根据字符串宽度重新构建标签。

对于第二种解决方案,您可以计算出字符串的大小

CGSize strSize = CGSizeZero; 

CGSize minSize = CGSizeZero; 

if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) 
{ 
    NSAttributedString *attributedText = [[[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: label.font}] autorelease]; 
    CGRect rect = [attributedText boundingRectWithSize:constraintSize 
               options:NSStringDrawingUsesLineFragmentOrigin 
               context:nil]; 
    strSize = rect.size; 
} 
else 
{ 
    strSize = [text sizeWithFont:label.font constrainedToSize:constraintSize]; 
} 
相关问题