ios 根据文本调整 UILabel 高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/446405/
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
Adjust UILabel height depending on the text
提问by Mustafa
Consider I have the following text in a UILabel
(a long line of dynamic text):
考虑我在UILabel
(一长串动态文本)中有以下文本:
Since the alien army vastly outnumbers the team, players must use the post-apocalyptic world to their advantage, such as seeking cover behind dumpsters, pillars, cars, rubble, and other objects.
由于外星军队的人数远远超过团队,玩家必须利用后世界末日世界的优势,例如在垃圾箱、柱子、汽车、瓦砾和其他物体后面寻找掩护。
I want to resize the UILabel's
height so that the text can fit in. I'm using following properties of UILabel
to make the text within to wrap.
我想调整UILabel's
高度,以便文本可以适应。我正在使用以下属性UILabel
来使文本换行。
myUILabel.lineBreakMode = UILineBreakModeWordWrap;
myUILabel.numberOfLines = 0;
Please let me know if I'm not heading in the right direction. Thanks.
如果我没有朝着正确的方向前进,请告诉我。谢谢。
回答by PyjamaSam
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
sizeWithFont constrainedToSize:lineBreakMode:
是使用的方法。如何使用它的示例如下:
//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;
回答by DonnaLea
You were going in the right direction. All you need to do is:
你正朝着正确的方向前进。您需要做的就是:
myUILabel.numberOfLines = 0;
myUILabel.text = @"Enter large amount of text here";
[myUILabel sizeToFit];
回答by Vitali Tchalov
In iOS 6 Apple has added a property to UILabelthat greatly simplifies dynamic vertical resizing of labels: preferredMaxLayoutWidth.
在 iOS 6 中,Apple 为UILabel添加了一个属性,大大简化了标签的动态垂直调整大小:preferredMaxLayoutWidth。
Using this property in combination with lineBreakMode = NSLineBreakByWordWrappingand sizeToFitmethod allows easily resize a UILabel instance to the height that accommodates the entire text.
将此属性与lineBreakMode = NSLineBreakByWordWrapping和sizeToFit方法结合使用,可以轻松地将 UILabel 实例的大小调整为适合整个文本的高度。
A quote from iOS documentation:
来自 iOS 文档的引用:
preferredMaxLayoutWidthThe preferred maximum width (in points) for a multiline label.
DiscussionThis property affects the size of the label when layout constraints are applied to it. During layout, if the text extends beyond the width specified by this property, the additional text is flowed to one or more new lines, thereby increasing the height of the label.
preferredMaxLayoutWidth多行标签的首选最大宽度(以磅为单位)。
讨论当布局约束应用于标签时,此属性会影响标签的大小。在布局过程中,如果文本超出此属性指定的宽度,则附加文本将流向一个或多个新行,从而增加标签的高度。
A sample:
一个样品:
...
UILabel *status = [[UILabel alloc] init];
status.lineBreakMode = NSLineBreakByWordWrapping;
status.numberOfLines = 5; // limits to 5 lines; use 0 for unlimited.
[self addSubview:status]; // self here is the parent view
status.preferredMaxLayoutWidth = self.frame.size.width; // assumes the parent view has its frame already set.
status.text = @"Some quite lengthy message may go here…";
[status sizeToFit];
[status setNeedsDisplay];
...
回答by Badal Shah
Check this work perfectly without adding Single line of code. (Using Autolayout)
在不添加单行代码的情况下完美地检查这项工作。(使用自动布局)
I made a demofor you according to your requirement. Download it from below link,
我根据您的要求为您制作了一个演示。从下面的链接下载它,
Step by Step Guide :-
分步指南:-
Step 1 :-Set constrain to UIView
第 1 步:-将约束设置为 UIView
1) Leading 2) Top 3) Trailing (From mainview)
1) 领先 2) 前 3) 尾随(来自主视图)
Step 2 :-Set constrain to Label 1
第 2 步:-将约束设置为标签 1
1) Leading 2) Top 3) Trailing (From it's superview)
1) 领先 2) 前 3) 落后(从它的超级视图)
Step 3 :-Set constrain to Label 2
第 3 步:-将约束设置为标签 2
1) Leading 2) Trailing (From it's superview)
1)领先 2)尾随(从它的超级视图)
Step 4 :-Most trickygive botton to UILabel from UIView .
第 4 步:-最棘手的是从 UIView 给 UILabel 赋予 botton。
Step 5 :-(Optional) Set constrain to UIButton
第 5 步:-(可选)将约束设置为 UIButton
1) Leading 2) Bottom 3) Trailing 4) Fixed Height (From mainview)
1) 前导 2) 底部 3) 尾随 4) 固定高度(来自主视图)
Output :-
输出 :-
Note :-Make sure you have set Number of lines =0 in Label property.
注意:-确保您在 Label 属性中设置了 Number of lines =0。
I hope this info enough to understand Autoresize UIView according to UILabel's height and Autoresize UILabel According to text.
我希望这些信息足以理解根据 UILabel 的高度自动调整 UIView 大小和根据文本自动调整 UILabel 大小。
回答by Pavithra Duraisamy
Instead doing this programmatically, you can do this in Storyboard/XIB while designing.
您可以在设计时在 Storyboard/XIB 中执行此操作,而不是以编程方式执行此操作。
- Set UIlabel's number of linesproperty to 0in attribute inspector.
- Then set width constraint/(or) leading and trailing constraint as per the requirement.
- Then set height constraintwith minimum value. Finally select the height constraint you added and in the size inspector the one next to attribute inspector, changethe height constraint's relationfrom equal to- greater than.
- 在属性检查器中将 UIlabel 的行数属性设置为0。
- 然后根据要求设置宽度约束/(或)前导和尾随约束。
- 然后用最小值设置高度约束。最后选择您添加的高度约束,并在尺寸检查器中属性检查器旁边的一个,将高度约束的关系从等于-大于更改为。
回答by iappdeveloper
Thanks guys for help, here is the code I tried which is working for me
感谢大家的帮助,这是我尝试过的对我有用的代码
UILabel *instructions = [[UILabel alloc]initWithFrame:CGRectMake(10, 225, 300, 180)];
NSString *text = @"First take clear picture and then try to zoom in to fit the ";
instructions.text = text;
instructions.textAlignment = UITextAlignmentCenter;
instructions.lineBreakMode = NSLineBreakByWordWrapping;
[instructions setTextColor:[UIColor grayColor]];
CGSize expectedLabelSize = [text sizeWithFont:instructions.font
constrainedToSize:instructions.frame.size
lineBreakMode:UILineBreakModeWordWrap];
CGRect newFrame = instructions.frame;
newFrame.size.height = expectedLabelSize.height;
instructions.frame = newFrame;
instructions.numberOfLines = 0;
[instructions sizeToFit];
[self addSubview:instructions];
回答by Vijay-Apple-Dev.blogspot.com
Solution to iOS7 prior and iOS7 above
iOS7之前和iOS7以上的解决方案
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import <UIKit/UIKit.h>
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define iOS7_0 @"7.0"
@interface UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel;
@end
//
// UILabel+DynamicHeight.m
// For StackOverFlow
//
// Created by Vijay on 24/02/14.
// Copyright (c) 2014 http://Vijay-Apple-Dev.blogspot.com. All rights reserved.
//
#import "UILabel+DynamicHeight.h"
@implementation UILabel (DynamicHeight)
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel{
NSAssert(self, @"UILabel was nil");
//Label text
NSString *aLabelTextString = [self text];
//Label font
UIFont *aLabelFont = [self font];
//Width of the Label
CGFloat aLabelSizeWidth = self.frame.size.width;
if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
//version < 7.0
return [aLabelTextString sizeWithFont:aLabelFont
constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
}
else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
//version >= 7.0
//Return the calculated size of the Label
return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : aLabelFont
}
context:nil].size;
}
return [self bounds].size;
}
@end
回答by pkarc
Since sizeWithFont is deprecated I use this one instead.
由于 sizeWithFont 已被弃用,因此我改用这个。
this one get label specific attributes.
这个获得标签特定的属性。
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:label.font}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){label.frame.size.width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return ceil(rect.size.height);
}
回答by Maverick
UILabel extension based on this answerfor Swift 4 and above
基于扩展的UILabel这个答案对于斯威夫特4及以上
extension UILabel {
func retrieveTextHeight () -> CGFloat {
let attributedText = NSAttributedString(string: self.text!, attributes: [NSFontAttributeName:self.font])
let rect = attributedText.boundingRect(with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil)
return ceil(rect.size.height)
}
}
Can be used like:
可以像这样使用:
self.labelHeightConstraint.constant = self.label.retrieveTextHeight()
回答by bbrame
Here is a category version:
这是一个类别版本:
UILabel+AutoSize.h#import
UILabel+AutoSize.h#import
@interface UILabel (AutoSize)
- (void) autosizeForWidth: (int) width;
@end
UILabel+AutoSize.m
UILabel+AutoSize.m
#import "UILabel+AutoSize.h"
@implementation UILabel (AutoSize)
- (void) autosizeForWidth: (int) width {
self.lineBreakMode = UILineBreakModeWordWrap;
self.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
CGSize expectedLabelSize = [self.text sizeWithFont:self.font constrainedToSize:maximumLabelSize lineBreakMode:self.lineBreakMode];
CGRect newFrame = self.frame;
newFrame.size.height = expectedLabelSize.height;
self.frame = newFrame;
}
@end