How to Calculate Uilabel Width Based on Text Length

How to calculate UILabel width based on text length?

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
constrainedToSize:maximumLabelSize
lineBreakMode:yourLabel.lineBreakMode];

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

this question might have your answer, it worked for me.


For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs =
[self.yourLabel.text
boundingRectWithSize:self.yourLabel.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{ NSFontAttributeName:self.yourLabel.font }
context:nil]
.size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

resizing UILabels based on total width of text

If Want to Make size of UILabel Based on TextSize and TextLength then use
intrinsicContentSize.

Below is sample code for that:

lblDemo.frame.size = lblDemo.intrinsicContentSize

Here lblDemo is IBOutlet of UILabel.

Objective c uilabel width based on text length

You might want to use [yourLabel sizeToFit]; or [yourLabel sizeThatFits: <#your target size#>];

sizeToFit resizes your label within it's current frame.size according to it's current text , font and the numberOfLines you provided.

Then you can change the size

[yourLabel sizeToFit];
CGRect rect = yourLabel.frame;
rect.size.width += 10;
yourLabel.frame = rect;

sizeThatFits:(CGSize)size doesn't resize your label but it returns the size that fits the size you pass as parameter.
sizeToFit uses sizeThatFits:(CGSize)size internally.

You can change size by doing this

CGSize exampleSize = (CGSize){300, 300};
CGSize fittingSize = [yourLabel sizeThatFits: exampleSize];
CGRect rect = yourLabel.frame;
rect.size.width = fittingSize.width;
rect.size.height = fittingSize.height;
yourLabel.frame = rect;

This should be working fine even if you are working with yourLabel.attributedText

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 calculate the width of a text string of a specific font and font-size?

You can do exactly that via the various sizeWithFont: methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):

NSString *someString = @"Hello World";
UIFont *yourFont = // [UIFont ...]
CGSize stringBoundingBox = [someString sizeWithFont:yourFont];

There are several variations of this method, eg. some consider line break modes or maximum sizes.

How to change UILabel width based on text length in iOS?

Although Keshav answer will work, it's deprecated

try:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};

CGRect rect = [textToMeasure boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];

Then use the Size of rect to determine your positioning and label size.

CGRect currentLabelFrame = self.label.frame;

currentLabelFrame.size.width = rect.size.width;

self.label.frame = currentLabelFrame;

How to change UILabel width based on text length in iOS Using Auto-Layouts

Select the First UILabel, set Leading, Top, bottom and set fixed width, then go to size Inspector -> select fixed width constraints -> Relation -> select Greater than or equal, example is give below,

Sample Image

Sample Image

select the Second UILabel, set Leading, Bottom, fixed width, then above same processs to be perform,

hope its helpful

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

Pixel Width of the text in a UILabel

NSString has a sizeWithAttributes: method that can be used for this. It returns a CGSize structure, so you could do something similar to the following to find the width of the text inside your label.

iOS 7 and higher

CGSize textSize = [[label text] sizeWithAttributes:@{NSFontAttributeName:[label font]}];

CGFloat strikeWidth = textSize.width;

iOS <7

Prior to iOS7, you had to use the sizeWithFont: method.

CGSize textSize = [[label text] sizeWithFont:[label font]];

CGFloat strikeWidth = textSize.width;

UILabel has a font property that you can use to dynamically get the font details for your label as i'm doing above.

Hope this helps :)



Related Topics



Leave a reply



Submit