Adjust Uilabel Height Depending on the 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

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

Adjust UILabel height by content in xamarin.ios

try this.

labelTitle = new UILabel ();
labelTitle.StyleTitle ();
labelTitle.TextAlignment = UITextAlignment.Center;
labelTitle.LineBreakMode = UILineBreakMode.WordWrap;
labelTitle.Lines = 0;

And now give the label center point.

Change the height of UILabel dynamically based on content

Using below you can get the height of the label

  • text - text of the label
  • font - font used in label
  • width - width of the label

    -(float) getHeightForText:(NSString*) text withFont:(UIFont*) font andWidth:(float) width{
    CGSize constraint = CGSizeMake(width , 20000.0f);
    CGSize title_size;
    float totalHeight;

    SEL selector = @selector(boundingRectWithSize:options:attributes:context:);
    if ([text respondsToSelector:selector]) {
    title_size = [text boundingRectWithSize:constraint
    options:NSStringDrawingUsesLineFragmentOrigin
    attributes:@{ NSFontAttributeName : font }
    context:nil].size;

    totalHeight = ceil(title_size.height);
    } else {
    title_size = [text sizeWithFont:font
    constrainedToSize:constraint
    lineBreakMode:NSLineBreakByWordWrapping];
    totalHeight = title_size.height ;
    }

    CGFloat height = MAX(totalHeight, 40.0f);
    return height;
    }

and create a frame using the height

CGRect frame = questionTitleLbl.frame;

float height = [self getHeightForText:questionTitleLbl.text
withFont:questionTitleLbl.font
andWidth:questionTitleLbl.frame.size.width];
float gap = 2;

cell.questionTitleLbl.frame = CGRectMake(frame.origin.x,
frame.origin.y,
frame.size.width,
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

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

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.



Related Topics



Leave a reply



Submit