How to Get the Height of a Uilabel in Swift

How to get the height of a UILabel in Swift?

it's simple, just call

label.bounds.size.height

Figure out size of UILabel based on String in Swift

Use an extension on String

Swift 3

extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

return ceil(boundingBox.height)
}

func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

return ceil(boundingBox.width)
}
}

and also on NSAttributedString (which is very useful at times)

extension NSAttributedString {
func height(withConstrainedWidth width: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

return ceil(boundingBox.height)
}

func width(withConstrainedHeight height: CGFloat) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

return ceil(boundingBox.width)
}
}

Swift 4 & 5

Just change the value for attributes in the extension String methods

from

[NSFontAttributeName: font]

to

[.font : font]

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

}

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

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
}

Sample Image

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 calculate the height of a UILabel?

In Swift 3

set BackgroundView Constraint like leading, trailing,top,bottom, please show image.

Sample Image

set UILabel Constraint like leading, trailing, top, bottom

and set it's property numberOfLines = 0

Sample Image

and after that your viewController class ViewDidLoad method write this code.

override func viewDidLoad() {
super.viewDidLoad()
//dynamic tablview
yourTablview.estimatedRowHeight = 83.0
yourTablview.rowHeight = UITableViewAutomaticDimension
}

I hope it's work for you.



Related Topics



Leave a reply



Submit