ios 如何动态计算 UILabel 高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27374612/
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
How do I calculate the UILabel height dynamically
提问by cdub
I have the following code:
我有以下代码:
label.numberOfLines = 0; // allows label to have as many lines as needed
label.text = @"some long text";
[label sizeToFit];
How do I get the height of label in points?
如何以点为单位获得标签的高度?
回答by Salman Zaidi
Use following method to calculate dynamic UILabel height:
使用以下方法计算动态 UILabel 高度:
- (CGFloat)getLabelHeight:(UILabel*)label
{
CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [label.text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:label.font}
context:context].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}
回答by Fabio Berger
The easiest way to get the height is sizeThatFits
. Use it like this:
获取高度的最简单方法是sizeThatFits
. 像这样使用它:
Objective-C
目标-C
CGFloat maxLabelWidth = 100;
CGSize neededSize = [label sizeThatFits:CGSizeMake(maxLabelWidth, CGFLOAT_MAX)];
Swift 3.0
斯威夫特 3.0
let maxLabelWidth: CGFloat = 100
let neededSize = label.sizeThatFits(CGSize(width: maxLabelWidth, height: CGFloat.greatestFiniteMagnitude))
The height your label needs is neededSize.height
.
Note that im using CGFLOAT_MAX
for the size height, to make sure the label has enough place to fit in the CGSize
.
您的标签需要的高度是neededSize.height
。
请注意,我使用CGFLOAT_MAX
的是尺寸高度,以确保标签有足够的位置以适合CGSize
.
The height of your label also depends on your width of the label, thats why I added maxLabelWidth
, it makes a difference if the label can be 100pt wide or 200pt.
标签的高度还取决于标签的宽度,这就是我添加的原因maxLabelWidth
,如果标签可以是 100pt 宽或 200pt,这会有所不同。
Hope this helps!
希望这可以帮助!
Edit:Make sure you set label.numberOfLines = 0;
otherwise neededSize
returns the size where the text is in a single line.
编辑:确保您设置label.numberOfLines = 0;
否则neededSize
返回文本在一行中的大小。
Edit:Added Swift version, although the naming is a bit weird, greatestFiniteMagnitude seems to be the correct equivalent for CGFLOAT_MAX.
编辑:添加了 Swift 版本,虽然命名有点奇怪,但 bestFiniteMagnitude 似乎是 CGFLOAT_MAX 的正确等效项。
回答by iHulk
回答by kishorer747
For those who want to estimate the size a label takes in a method which estimates header / cell height in UICollectionView or UITableView, follow this:
对于那些想要在 UICollectionView 或 UITableView 中估计标题/单元格高度的方法中估计标签大小的人,请遵循以下步骤:
- Set maxWidth that your label will take
- Create a new UILabel and set numberOfLines to 0
- Add Font attributes like custom font name and font size if using custom fonts
- Set text for this label and get estimated height using sizeThatFits. Label height is
neededHeight.height
- 设置您的标签将采用的 maxWidth
- 创建一个新的 UILabel 并将 numberOfLines 设置为 0
- 如果使用自定义字体,则添加自定义字体名称和字体大小等字体属性
- 为该标签设置文本并使用 sizeThatFits 获取估计高度。标签高度为
neededHeight.height
SwiftVersion
迅捷版
let maxLabelWidth:CGFloat = collectionView.frame.width - 20
let label = UILabel()
label.numberOfLines = 0
let addressFont = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 12.0)! ]
let addr = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
label.attributedText = NSMutableAttributedString(string: addr , attributes: addressFont )
let neededSize:CGSize = label.sizeThatFits(CGSizeMake(maxLabelWidth, CGFloat.max))
let labelHeight = neededSize.height
Thanks to @FabioBerger
感谢@FabioBerger
回答by sohil
You can Create Label dynamically :
您可以动态创建标签:
-(CGRect)newLableSize:(NSString *)lableString
{
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
CGFloat tempwidth = YourStaticLabelWidth * ScreenWidth / 320;
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects: lableString,nil];
CGRect newLabelsize = [[array objectAtIndex:0] boundingRectWithSize:CGSizeMake(tempwidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:selectFont,NSParagraphStyleAttributeName:paragraphStyle} context:nil];
NSLog(@"New Label Size Width : %f",newLabelsize.size.width);
NSLog(@"New Label Size Height : %f",newLabelsize.size.height);
return newLabelsize;
}
回答by Shayno
I edited Salman Zaidi's answer a little to make it work better for myself. It works well if you don't have direct access to a label, like when you are trying to get label height in heightForRowAtIndexPath:
我稍微编辑了 Salman Zaidi 的答案,以使其更适合我自己。如果您无法直接访问标签,则效果很好,例如当您尝试获取标签高度时heightForRowAtIndexPath:
-(CGFloat)getLabelHeight:(CGSize)labelSize string: (NSString *)string font: (UIFont *)font{
CGSize size;
NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
CGSize boundingBox = [string boundingRectWithSize:labelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:context].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}
回答by Vinicius Carvalho
I'm adjust height, with 2 lines in my label
我正在调整高度,在我的 2 行 label
lblUserQuestion.preferredMaxLayoutWidth = 100.0f;
lblUserQuestion.preferredMaxLayoutWidth = 100.0f;
100.0f, it's a size i wanted, and another line,
100.0f,这是我想要的尺寸,还有另一条线,
[lblUserQuestion sizeToFit];
[lblUserQuestion sizeToFit];
My method complete is,
我的完整方法是,
UILabel *lblUserQuestion = [[UILabel alloc] initWithFrame:CGRectMake(61, 25, self.frame.size.width-61-20, 37.0f)];
lblUserQuestion.numberOfLines= 0;
lblUserQuestion.font =[UIFont fontWithName:@"HelveticaNeue-Thin" size:14.];
lblUserQuestion.adjustsFontSizeToFitWidth = YES;
lblUserQuestion.minimumScaleFactor = 0.5;
lblUserQuestion.preferredMaxLayoutWidth= 100.0f;
lblUserQuestion.text = _photoToVote.label;
回答by Sargis Gevorgyan
- (CGFloat)getTextHeightByWidth:(NSString*)text textFont:(UIFont*)textFont textWidth:(float)textWidth {
if (!text) {
return 0;
}
CGSize boundingSize = CGSizeMake(textWidth, CGFLOAT_MAX);
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{ NSFontAttributeName: textFont }];
CGRect rect = [attributedText boundingRectWithSize:boundingSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
CGSize requiredSize = rect.size;
return requiredSize.height;
}
- (CGFloat)getTextWidthByHeight:(NSString*)text textFont:(UIFont*)textFont textHeight:(float)textHeight {
if (!text) {
return 0.0f;
}
CGSize boundingSize = CGSizeMake(CGFLOAT_MAX, textHeight);
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text
attributes:@{ NSFontAttributeName: textFont }];
CGRect rect = [attributedText boundingRectWithSize:boundingSize
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize requiredSize = rect.size;
return requiredSize.width;
}
回答by Ashokios
- (CGFloat)getLabelsize:(UILabel *)label
{
CGSize maxSize = CGSizeMake(label.frame.size.width, 9999);
CGSize requiredSize = [label sizeThatFits:maxSize];
return requiredSize.height;
}
回答by Sandeep Singh
Use this function
使用这个功能
+ (CGFloat)heightForText:(NSString*)text font:(UIFont*)font withinWidth:(CGFloat)width {
CGSize constraint = CGSizeMake(width, 20000.0f);
CGSize size;
CGSize boundingBox = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil].size;
size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));
return size.height;
}