Adjust Uilabel Height to Text

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;

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

Setting the height of UIlabel

You can set label's height constraint >= 0. Label will update it's size to the content, and if text is missing height will be 0.

Sample Image

Resizing the height of UILabel to fit text

The easiest way to do that is using autolayout constraints. You are using awakeFromNib, so I assume you have that cell somewhere in your Interface Builder (xib or storyboard file).

If you can avoid it, never set up your views in your code. It's far easier to do it in the Interface Builder.

  1. Find your label and set up its attributes (font, color, line break mode etc.) in the Interface Builder.

  2. Add a width constraint (or constraints to left and right margins, depending on what you want).

  3. Add a height constraint, change its relation from = (equals) to < (less than).

You are done, no code is needed.

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 
@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;
}

UILabel height depending on font size

When UILabel is set to auto-adjust font size to fit, it does NOT auto-adjust the height of itself.

You have a couple options:

  1. set Baseline to Align Centers, and just accept that you will have top and bottom padding

  2. use code to calculate the "scaled font size" and update the font size of the label

How to adjust a UILabel font size based on the height available to the label

You can set the font to automatically fill the size of a label, and optionally not go below a minimum font size. Just set adjustsFontSizeToFitWidth to YES. Check out the UILabel Class Reference if you need more information.

Although the boolean is called "adjustsFontSizeToWidth," it really means the largest size for the height of the label, that will stay on one line of the label (or however many lines you specify).

Subclassed UILabel and overrode layoutSubviews. Then each time the UILabel gets its size changed, the font size is recalculated:

import Foundation
import UIKit

class LabelWithAdaptiveTextHeight: UILabel {

override func layoutSubviews() {
super.layoutSubviews()
font = fontToFitHeight()
}

// Returns an UIFont that fits the new label's height.
private func fontToFitHeight() -> UIFont {

var minFontSize: CGFloat = DISPLAY_FONT_MINIMUM // CGFloat 18
var maxFontSize: CGFloat = DISPLAY_FONT_BIG // CGFloat 67
var fontSizeAverage: CGFloat = 0
var textAndLabelHeightDiff: CGFloat = 0

while (minFontSize <= maxFontSize) {
fontSizeAverage = minFontSize + (maxFontSize - minFontSize) / 2

if let labelText: NSString = text {
let labelHeight = frame.size.height

let testStringHeight = labelText.sizeWithAttributes(
[NSFontAttributeName: font.fontWithSize(fontSizeAverage)]
).height

textAndLabelHeightDiff = labelHeight - testStringHeight

if (fontSizeAverage == minFontSize || fontSizeAverage == maxFontSize) {
if (textAndLabelHeightDiff < 0) {
return font.fontWithSize(fontSizeAverage - 1)
}
return font.fontWithSize(fontSizeAverage)
}

if (textAndLabelHeightDiff < 0) {
maxFontSize = fontSizeAverage - 1

} else if (textAndLabelHeightDiff > 0) {
minFontSize = fontSizeAverage + 1

} else {
return font.fontWithSize(fontSizeAverage)
}
}
}
return font.fontWithSize(fontSizeAverage)
}
}


Related Topics



Leave a reply



Submit