[英]How to get the correct width of a UILabel after the text has been set?
我得到了 UILabel 的寬度 [在設置文本之后]:
myUILabel.frame.width
但它總是相同的寬度,無論它是否包含字符串: "Hello."
或字符串: "Hello everyone on this planet."
. 但是 UILabel 需要與第二個字符串有更大的寬度。
試試myUILabel.intrinsicContentSize()
。 當然,請確保先設置字體。
你應該使用[label sizeToFit]
sizeToFit
on label 將拉伸標簽以容納文本。
另一種解決方案是計算字符串的寬度並根據字符串寬度重新構建標簽。
對於第二個解決方案,您可以將字符串的大小計算為
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];
}
嘗試
myUILabel.intrinsicContentSize().width
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.