How to calculate UILabel height dynamically?
Try this
// UILabel *myLabel;
CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
CGFloat labelHeight = labelSize.height;
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping].height/16;
// '16' is font size
or
int lines = labelHeight/16;
NSLog(@"lines count : %i \n\n",lines);
or
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font
By Using Categories, Just Create the category class named as
UILabel+UILabelDynamicHeight.h
UILabel+UILabelDynamicHeight.m
No more tension about the height calculation. Please review the below implementation.
Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#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 SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define iOS7_0 @"7.0"
UILabel+UILabelDynamicHeight.h
#import <UIKit/UIKit.h>
@interface UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size the Multi line Label
/*====================================================================*/
/* Calculate the size 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+UILabelDynamicHeight.m
#import "UILabel+UILabelDynamicHeight.h"
@implementation UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size,bounds,frame of the Multi line Label
/*====================================================================*/
/* 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{
//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
How do I calculate the UILabel height dynamically
Use following method to calculate dynamic UILabel height:
- (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;
}
Adjust UILabel height depending on the text
sizeWithFont constrainedToSize:lineBreakMode:
is the method to use. An example of how to use it is below:
//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;
How to get exactly height of UILabel with line space?
You can get the exact height of UILabel with exactly passing the same font size and type and doing some calculations.
Here I used a UILabel with Helvetica font with font size 16.
Objective C
- (CGFloat)requiredHeight:(NSString*)labelText{
UIFont *font = [UIFont fontWithName:@"Helvetica" size:16.0];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, CGFLOAT_MAX)];
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = font;
label.text = labelText;
[label sizeToFit];
return label.frame.size.height;
}
Output
CGFloat size = [self requiredHeight:@"iOS Rocks"];
NSLog(@"%f",size);
size = [self requiredHeight:@"iOS Rocks\n"];
NSLog(@"%f",size);
Console Output
2016-04-10 01:37:46.812 testPro[6093:327503] 18.500000
2016-04-10 01:37:46.814 testPro[6093:327503] 37.000000
Swift 2.2
func requiredHeight(labelText:String) -> CGFloat {
let font = UIFont(name: "Helvetica", size: 16.0)
let label:UILabel = UILabel(frame: CGRectMake(0, 0, 200, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.font = font
label.text = labelText
label.sizeToFit()
return label.frame.height
}
Edit
Swift 3.0
func requiredHeight(labelText:String) -> CGFloat {
let font = UIFont(name: "Helvetica", size: 16.0)
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: .max))
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = font
label.text = labelText
label.sizeToFit()
return label.frame.height
}
Adjust UILabel height to text
I've just put this in a playground and it works for me.
Updated for Swift 4.0
import UIKit
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
let font = UIFont(name: "Helvetica", size: 20.0)
var height = heightForView("This is just a load of text", font: font, width: 100.0)
Swift 3:
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
How to get the height of a UILabel in Swift?
it's simple, just call
label.bounds.size.height
How to get the dynamic height of UIView which contains two or more UILabels vertically?
I think your answer lies in layoutIfNeeded
and let me explain why
Consider my storyboard set up to set up a Dynamic height UIView which should set its height automatically based on the UILabels within it, note that I did not set the height anchor and so it gives me constraint errors which you can ignore for now as they will be resolved once we are done setting up.
Next I add two labels to this view which have numberOfLines = 0
Top Label constraints
Bottom Label constraints
After this, the constraint errors go away and notice the height of the view in which the labels are contained in is 82
:
Now I add this code which dynamically changes the text in the label
class DynamicHeightVC: UIViewController
{
@IBOutlet var myView: UIView!
@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
var longText = """
Some really long text that should make the UI label
expand beyond a few lines and make the UIView expand
along with it.
"""
var reallyLongText = """
Some really long text that should make the UI label
expand beyond a few lines and make the UIView expand
along with it. Some really long text that should make
the UI label expand beyond a few lines and make the
UIView expand along with it.
"""
override func viewDidLoad()
{
super.viewDidLoad()
labelOne.text = longText
labelTwo.text = reallyLongText
print("View height \(myView.frame.height)")
}
}
The output is View height 82.0
which is the value we saw on the storyboard and it is clearly wrong as the view's height is bigger:
So the issue is once you change / update the text, the constraints get updated and the frames will get updated at a later / different iteration of the main run loop which might not be useful to you since you want to do some calculations with it now.
If you want the frames to be updated in the next turn of the update cycle within the main run loop, you need to call view.setNeedsLayout()
.
If you want the frames to be updated immediately, you need to call view.layoutIfNeeded()
After making this change, the code is as follows:
class DynamicHeightVC: UIViewController
{
@IBOutlet var myView: UIView!
@IBOutlet weak var labelOne: UILabel!
@IBOutlet weak var labelTwo: UILabel!
var longText = """
Some really long text that should make the UI label
expand beyond a few lines and make the UIView expand
along with it.
"""
var reallyLongText = """
Some really long text that should make the UI label
expand beyond a few lines and make the UIView expand
along with it. Some really long text that should make
the UI label expand beyond a few lines and make the
UIView expand along with it.
"""
override func viewDidLoad()
{
super.viewDidLoad()
labelOne.text = longText
labelTwo.text = reallyLongText
view.layoutIfNeeded()
print("Label 1 height \(labelOne.frame.height)")
print("Label 2 height \(labelTwo.frame.height)")
print("View height \(myView.frame.height)")
}
}
And now the console displays the correct, updated height:
Label 1 height 101.5
Label 2 height 183.0
View height 284.5
Related Topics
How to Draw a Transparent Stroke (Or Anyway Clear Part of an Image) on the Iphone
How to Make Return Key on iPhone Make Keyboard Disappear
How to Find Out Distance Between Coordinates
Convert Coordinates to City Name
Check If Location Services Are Enabled
How to Change the Height of a Uinavigationbar in Storyboard Without Using a Uinavigationcontroller
What Advantage(S) Does Dispatch_Sync Have Over @Synchronized
The App Delegate Must Implement the Window Property If It Wants to Use a Main Storyboard File Swift
Xcode 6 Save for Enterprise Deployment Does Not Create Plist for IPA Anymore
Google Maps iOS Sdk, Getting Directions Between 2 Locations
Xcode 8 - Missing Files Warnings
Grouped Uitableview Remove Outer Separator Line
How to Set Status Bar Style in Swift 3
Hide Device Volume Hud View While Adjusitng Volume with Mpvolumeview Slider
Delivery Report of Sending Remote Push Notifications Using Apns - iOS
How to Save List of Object in User Default
Set Custom Images to the Uibarbuttonitem But It Doesn't Show Any Image