根据文本动态获取 UILabel 的高度为 iOS 7.0 和 iOS 6.1 返回不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20068849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically getting height of UILabel according to Text return different Value for iOS 7.0 and iOS 6.1
提问by Sumeet Mourya
I am using the this method for getting the height of the UILabel Dynamically:
我正在使用此方法动态获取 UILabel 的高度:
+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size: (CGSize)LabelSize{
label.numberOfLines = 0;
CGSize labelSize = [label.text sizeWithFont:fontForLabel constrainedToSize:LabelSize lineBreakMode:NSLineBreakByCharWrapping];
return (labelSize);
}
With this solution I am getting the exact size of UILabel if my code is running on below iOS 8 but if I run my application on iOS7 then it is returns a different value.
使用此解决方案,如果我的代码在 iOS 8 以下运行,我将获得 UILabel 的确切大小,但如果我在 iOS7 上运行我的应用程序,则它返回不同的值。
回答by preetam
You have to dynamically set the frame, like below:
您必须动态设置框架,如下所示:
Tested on iOS 6 to iOS 12.2
在 iOS 6 到 iOS 12.2 上测试
Swift:
迅速:
let constrainedSize = CGSize(width: self.titleLable.frame.size.width, height:9999)
let attributesDictionary = [NSAttributedString.Key.font: UIFont.init(name: "HelveticaNeue", size: 11.0)]
let string = NSAttributedString.init(string: "textToShow", attributes: attributesDictionary as [NSAttributedString.Key : Any])
var requiredHeight = string.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, context: nil)
if (requiredHeight.size.width > self.titleLable.frame.size.width) {
requiredHeight = CGRect(x: 0, y: 0, width: self.titleLable.frame.size.width, height: requiredHeight.size.height)
}
var newFrame = self.titleLable.frame
newFrame.size.height = requiredHeight.size.height
self.titleLable.frame = newFrame
Objective C:
目标 C:
CGSize constrainedSize = CGSizeMake(self.resizableLable.frame.size.width , 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:@"HelveticaNeue" size:11.0], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"textToShow" attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > self.resizableLable.frame.size.width) {
requiredHeight = CGRectMake(0,0, self.resizableLable.frame.size.width, requiredHeight.size.height);
}
CGRect newFrame = self.resizableLable.frame;
newFrame.size.height = requiredHeight.size.height;
self.resizableLable.frame = newFrame;
回答by Andrew Bennett
Here's a total solution for width and height. Put these in your AppDelegate:
这是宽度和高度的整体解决方案。将这些放在你的 AppDelegate 中:
+(void)fixHeightOfThisLabel:(UILabel *)aLabel
{
aLabel.frame = CGRectMake(aLabel.frame.origin.x,
aLabel.frame.origin.y,
aLabel.frame.size.width,
[AppDelegate heightOfTextForString:aLabel.text
andFont:aLabel.font
maxSize:CGSizeMake(aLabel.frame.size.width, MAXFLOAT)]);
}
+(CGFloat)heightOfTextForString:(NSString *)aString andFont:(UIFont *)aFont maxSize:(CGSize)aSize
{
// iOS7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
CGSize sizeOfText = [aString boundingRectWithSize: aSize
options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes: [NSDictionary dictionaryWithObject:aFont
forKey:NSFontAttributeName]
context: nil].size;
return ceilf(sizeOfText.height);
}
// iOS6
CGSize textSize = [aString sizeWithFont:aFont
constrainedToSize:aSize
lineBreakMode:NSLineBreakByWordWrapping];
return ceilf(textSize.height;
}
+(void)fixWidthOfThisLabel:(UILabel *)aLabel
{
aLabel.frame = CGRectMake(aLabel.frame.origin.x,
aLabel.frame.origin.y,
[AppDelegate widthOfTextForString:aLabel.text
andFont:aLabel.font
maxSize:CGSizeMake(MAXFLOAT, aLabel.frame.size.height)],
aLabel.frame.size.height);
}
+(CGFloat)widthOfTextForString:(NSString *)aString andFont:(UIFont *)aFont maxSize:(CGSize)aSize
{
// iOS7
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
{
CGSize sizeOfText = [aString boundingRectWithSize: aSize
options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes: [NSDictionary dictionaryWithObject:aFont
forKey:NSFontAttributeName]
context: nil].size;
return ceilf(sizeOfText.width);
}
// iOS6
CGSize textSize = [aString sizeWithFont:aFont
constrainedToSize:aSize
lineBreakMode:NSLineBreakByWordWrapping];
return ceilf(textSize.width);
}
then to use this, set the label's text:
然后使用它,设置标签的文本:
label.numberOfLines = 0;
label.text = @"Everyone loves Stack OverFlow";
and call:
并调用:
[AppDelegate fixHeightOfThisLabel:label];
Note: label's numberOfLines has to be set to 0. Hope that helps.
注意:标签的 numberOfLines 必须设置为 0。希望有帮助。
回答by liamnichols
if you are using any of the system fonts, they changed in iOS 7 so they would be different sizes.
如果您使用任何系统字体,它们在 iOS 7 中发生了变化,因此它们的大小会有所不同。
Also, sizeWithFont:constrainedToSize:lineBreakMode:
is deprecated in iOS 7. Use sizeWithAttributes:instead (if you are on iOS 7)
此外,sizeWithFont:constrainedToSize:lineBreakMode:
在 iOS 7 中已弃用。使用sizeWithAttributes:代替(如果您使用的是 iOS 7)
回答by stackOverFlew
Accepted answer didn't satisfy me so I had to dig this up in my code:
接受的答案并没有让我满意,所以我不得不在我的代码中挖掘它:
CGSize possibleSize = [string sizeWithFont:[UIFont fontWithName:@"HelveticaNeue" size:10] //font you are using
constrainedToSize:CGSizeMake(skillsMessage.frame.size.width,9999)
lineBreakMode:NSLineBreakByWordWrapping];
CGRect newFrame = label.frame;
newFrame.size.height = possibleSize.height;
label.frame = newFrame;
回答by Armin
The accepted answer is too long. You can use the following:
接受的答案太长了。您可以使用以下内容:
+(CGSize) GetSizeOfLabelForGivenText:(UILabel*)label Font:(UIFont*)fontForLabel Size: (CGSize) constraintSize{
label.numberOfLines = 0;
CGRect labelRect = [label.text boundingRectWithSize:constraintSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:fontForLabel} context:nil];
return (labelRect.size);
}
回答by Js Lim
I all the time use sizeThatFits:
我一直在用 sizeThatFits:
CGRect frame = myLabel.frame;
CGSize constraint = CGSizeMake(CGRectGetWidth(myLabel.frame), 20000.0f);
CGSize size = [myLabel sizeThatFits:constraint];
frame.size.height = size.height;
myLabel.frame = frame;
You can try this
你可以试试这个
回答by AlexKoren
Super simple. Just get the area of the text, divide by width, then round up to the nearest height that will fit your font.
超级简单。只需获取文本的区域,除以宽度,然后四舍五入到适合您的字体的最接近的高度。
+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {
CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:font}];
CGFloat area = size.height * size.width;
CGFloat height = roundf(area / width);
return ceilf(height / font.lineHeight) * font.lineHeight;
}
Very much a plug and play solution. I use it in a helper class a lot, especially for dynamically sized UITableViewCells.
非常多的即插即用解决方案。我在辅助类中经常使用它,特别是对于动态大小的 UITableViewCells。
Hope this helps others in the future!
希望这可以帮助其他人在未来!
回答by Zulqarnain
I have a situation where i need to set the height of label dynamically according to text. I am using Xcode 7.1 and my project deployment target is 7.0 but i tested it on iOS 9 simulator and following solution works for me. Here is the solution: First of of you will create a dictionary like this:
我有一种情况,我需要根据文本动态设置标签的高度。我正在使用 Xcode 7.1,我的项目部署目标是 7.0,但我在 iOS 9 模拟器上对其进行了测试,以下解决方案对我有用。这是解决方案:首先,您将创建一个这样的字典:
NSDictionary *attributes = @{NSFontAttributeName:self.YOUR_LABEL.font};
now we will calculate the height and width for our text and pass the newly created dictionary.
现在我们将计算文本的高度和宽度并传递新创建的字典。
CGRect rect = [YOUR_TEXT_STRING boundingRectWithSize:CGSizeMake(LABEL_WIDTH, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
Then we will set the frame of our LABEL:
然后我们将设置我们的 LABEL 的框架:
self.YOUR_LABEL.frame = CGRectMake(self.YOUR_LABEL.frame.origin.x, self.YOUR_LABEL.frame.origin.y, self.YOUR_LABEL.frame.size.width, rect.size.height);
THIS IS HOW I SUCCESSFULLY SET THE FRAME OF MY LABEL ACCORDING TO TEXT.
这就是我根据文本成功设置标签框架的方式。
回答by Ladd.c
This method is used and tested by me from iOS 7 to iOS 11.4
这个方法是我从iOS 7到iOS 11.4使用和测试的
+ (CGFloat)getLabelHeight:(UILabel*)label
{
NSParameterAssert(label);
CGSize limitLabel = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize labelBox = [label.text boundingRectWithSize: limitLabel
options: NSStringDrawingUsesLineFragmentOrigin
attributes: @{ NSFontAttributeName:label.font }
context: context].size;
size = CGSizeMake(ceil(labelBox.width), ceil(labelBox.height));
return size.height;
}
So you can use like this:
所以你可以这样使用:
CGFloat sizeOfFontTest = 12.0;
UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(0, 0, 100, 0)];
[testLabel setFont: [UIFont systemFontOfSize: sizeOfFontTest]];
[testLabel setText: @"Hello Stackoverflow Large String Example"];
CGFloat heightTestLabel = [self getLabelHeight: testLabel];
[testLabel setFrame: CGRectMake(testLabel.frame.origin.x, testLabel.frame.origin.y, testLabel.frame.size.width, heightAddrsLab)];
[testLabel setNumberOfLines: sizeOfFontTest / heightTestLabel];
回答by Groot
The method sizeWithFont:constrainedToSize:lineBreakMode:
is deprecated in iOS7.
You should use sizeWithAttributes:
instead.
该方法sizeWithFont:constrainedToSize:lineBreakMode:
在 iOS7 中已弃用。你应该sizeWithAttributes:
改用。
Example:
例子:
NSDictionary *fontAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:15]};
CGSize textSize = [self.myLabel.text sizeWithAttributes:fontAttributes];
CGFloat textWidth = textSize.width;
CGFloat textHeight = textSize.height;