Why doesn't this work? It always returns 18 no matter the length of the string. There is this thread, but not a definitive answer.
NSString * t = #"<insert super super long string here>";
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] forWidth:285 lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"size.height is %f and text is %#", size.height, t);
Thanks,
Todd
Use sizeWithFont:constrainedToSize:lineBreakMode: instead.
NSString * t = #"<insert super super long string here>";
CGSize constrainSize = CGSizeMake(285, MAXFLOAT);
CGSize size = [t sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:constrainSize lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"size.height is %f and text is %#", size.height, t);
DEPRECATED Method: NS_DEPRECATED_IOS(2_0, 7_0)
- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:");
Example
CGSize titleTextSize = [self.titleLabel.text sizeWithFont:self.myLabel.font forWidth:myLabelWidth lineBreakMode:NSLineBreakByTruncatingTail];
New Approach
Use :
- (CGRect)boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary<NSString *,
id> *)attributes
context:(NSStringDrawingContext *)context
Example:
// Create a paragraph style with the desired line break mode
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
// Create the attributes dictionary with the font and paragraph style
NSDictionary *attributes = #{
NSFontAttributeName:self.myLabel.font,
NSParagraphStyleAttributeName:paragraphStyle
};
// Call boundingRectWithSize:options:attributes:context for the string
CGRect textRect = [self.countLabel.text boundingRectWithSize:CGSizeMake(widthOfMyLabel, 999999.0f)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
See Appple Doc
CGSize size = [t sizeWithFont:[UIFont fontWithName:#"Arial-BoldMT" size:16.0] constrainedToSize:CGSizeMake(220,500) lineBreakMode:UILineBreakModeWordWrap];
Related
This question already has answers here:
Replacement for deprecated sizeWithFont: in iOS 7?
(20 answers)
Closed 9 years ago.
I am using the below code to calculate the height of a label from string length. Im using xcode 5.0 and it works fine in iOS 6 simulator but it's not working well in iOS 7.
NSString* str = [[array objectAtIndex:i]valueForKey:#"comment"];
CGSize size = [className sizeWithFont:[UIFont systemFontOfSize:15]
constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap];
Height_1 = size.height;
If there is any solution for iOS 7 then please help.
Thanks in Advance
Well here is a solution I use for calculating the height for iOS 6 and iOS 7, and I have passed few arguments to make it reusable.
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
/**
* This method is used to calculate height of text given which fits in specific width having font provided
*
* #param text Text to calculate height of
* #param widthValue Width of container
* #param font Font size of text
*
* #return Height required to fit given text in container
*/
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font
{
CGFloat result = font.pointSize + 4;
if (text)
{
CGSize textSize = { widthValue, CGFLOAT_MAX }; //Width and height of text area
CGSize size;
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0"))
{
//iOS 7
CGRect frame = [text boundingRectWithSize:textSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:font }
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
}
else
{
//iOS 6.0
size = [text sizeWithFont:font constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
}
result = MAX(size.height, result); //At least one row
}
return result;
}
Hope this helps and yes any suggestions are appreciated. Happy Coding :)
For iOS 7 and above use below method.
+ (CGSize)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGSize size = CGSizeZero;
if (text) {
//iOS 7
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{ NSFontAttributeName:font } context:nil];
size = CGSizeMake(frame.size.width, frame.size.height + 1);
}
return size;
}
Try using this
#define FONT_SIZE 15.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 20.0f
NSString *text;
CGSize constraint;
CGSize size;
CGFloat height;
text = [[array objectAtIndex:i]valueForKey:#"comment"];
constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGRect textRect = [text boundingRectWithSize:constraint
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE]}
context:nil];
size = textRect.size;
height = size.height;
sizeWithFont
is deprecated. Use
[string sizeWithAttributes:#{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
instead
Use Below Code to get the height of the Label
CGSize szMaxCell = CGSizeMake(220, 2999);
UIFont *font = [UIFont systemFontOfSize:14.0f]; // whatever font you're using to display
CGSize szCell = [yourString sizeWithFont:font constrainedToSize:szMaxCell lineBreakMode:NSLineBreakByWordWrapping];
When I run the following code (iOS 6.1 SDK):
UIFont *font = [UIFont fontWithName:#"Avenir" size:12.0];
NSString *text1 = #"Short Label";
NSString *text2 = #"Long Label Whose Text Will Be Truncated Because It Is Too Long For The View";
CGSize text1Size = [text1 sizeWithFont:font
constrainedToSize:
CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByTruncatingTail];
CGSize text2Size = [text2 sizeWithFont:font
constrainedToSize:
CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByTruncatingTail];
NSLog(#"Text 1 Size: %f %f", text1Size.width, text1Size.height);
NSLog(#"Text 2 Size: %f %f", text2Size.width, text2Size.height);
The log output is:
Text 1 Size: 62.000000 17.000000
Text 2 Size: 300.000000 34.000000
Why are the heights different, here? In either case, it's one line of text; just one is truncated, the other is not.
Thanks!
The height is different because you gave it CGFLOAT_MAX as the height, so the method tries to figure out what size the text will be by breaking the text into multiple lines. In this case, apparently, two lines will be enough to contain that string in the width supplied.
This question has asked many times, however I have not clear, got wrong output. So please anyone help..
CGSize maximumSize = CGSizeMake(208, 21);
UIFont *myFont = [UIFont fontWithName:#"Helvetica" size:14];
CGSize myStringSize = [my_string sizeWithFont:myFont
constrainedToSize:maximumSize
lineBreakMode:self.my_label.lineBreakMode];
my_label.numberOfLines = 0;
my_label.frame.size = myStringSize;
I have a label of size (208, 21), I have used the following code to get actual height required for NSString with respect to my label width, I want fixed width, only height need to vary so I can set in label. But it always give lower height than actual.. Am I doing anything wrong here..
thanks..
In your example use a maximum size with a (very) large height instead of restricting the height:
CGSize maximumSize = CGSizeMake(208, CGFLOAT_MAX);
This way there will always be enough height to expand to, while limiting the width to the width you actually want.
Try this :
-(CGSize) calculateWidthOfString:(NSString*)textString withFont:(UIFont*)font
{
CGSize maximumSize = CGSizeMake(9999, 22);
CGSize size = [textString sizeWithFont:font
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
call this function with stringObject and Font Name, Size
it returns width of string with constant height "22" change this value as u want.
hope this will helps u.
+ (CGSize) calculateLabelHeightWith:(CGFloat)width text:(NSString*)textString
{
CGSize maximumSize = CGSizeMake(width, 9999);
CGSize size = [textString sizeWithFont:[UIFont fontWithName:#"Helvetica" size:24]
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
+ (CGSize) calculateLabelWidthOfString:(NSString*)textString withFont:(UIFont*)font
{
CGSize maximumSize = CGSizeMake(9999, 22);
CGSize size = [textString sizeWithFont:font
constrainedToSize:maximumSize
lineBreakMode:UILineBreakModeWordWrap];
return size;
}
use these two for height or width
How can I adjust the label Width according to the text? If text length is small I want the label width small...If text length is small I want the label width according to that text length. Is it possible?
Actually I have Two UIlabels. I need to place these two nearby. But if the first label's text is too small there will be a big gap. I want to remove this gap.
//use this for custom font
CGFloat width = [label.text sizeWithFont:[UIFont fontWithName:#"ChaparralPro-Bold" size:40 ]].width;
//use this for system font
CGFloat width = [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;
label.frame = CGRectMake(point.x, point.y, width,height);
//point.x, point.y -> origin for label;
//height -> your label height;
Function sizeWithFont: is deprecated in iOS 7.0, so you have to use sizeWithAttributes: for iOS 7.0+. Also to suport older versions, this code below can be used:
CGFloat width;
if ([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
{
width = [text sizeWithFont:[UIFont fontWithName:#"Helvetica" size:16.0 ]].width;
}
else
{
width = ceil([text sizeWithAttributes:#{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:16.0]}].width);
}
Using function ceil() on result of sizeWithAttributes: is recommended by Apple documentation:
"This method returns fractional sizes; to use a returned size to size views, you must raise its value to the nearest higher integer using the ceil function."
sizeWithAttributes
// In swift 2.0
let lblDescription = UILabel(frame: CGRectMake(0, 0, 200, 20))
lblDescription.numberOfLines = 0
lblDescription.text = "Sample text to show its whatever may be"
lblDescription.sizeToFit()
// Its automatically Adjust the height
Try these options,
UIFont *myFont = [UIFont boldSystemFontOfSize:15.0];
// Get the width of a string ...
CGSize size = [#"Some string here" sizeWithFont:myFont];
// Get the width of a string when wrapping within a particular width
NSString *mystring = #"some strings some string some strings...";
CGSize size = [mystring sizeWithFont:myFont
forWidth:150.0
lineBreakMode:UILineBreakModeWordWrap];
You can also try with [label sizeToFit]; Using this method, you can set frame of two labels as,
[firstLabel sizeToFit];
[secondLabel sizeToFit];
secondLabel.frame = CGRectMake(CGRectGetMaxX(firstLabel.frame), secondLabel.origin.y, secondLabel.frame.size.width, secondLabel.frame.size.height);
sizeWithFont constrainedToSize:lineBreakMode: is the original method to use. Here is an example of how to use it is below:
//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);
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;
just use to if you using constrain in your view or xib or cell
[LBl sizeToFit];
if its not working then
dispatch_async(dispatch_get_main_queue(), ^{
[LBl sizeToFit];
});
Try the following:
/* Consider these two labels as the labels that you use,
and that these labels have been initialized */
UILabel* firstLabel;
UILabel* secondLabel;
CGSize labelSize = [firstLabel.text sizeWithFont:[UIFont systemFontOfSize:12]];
//change the font size, or font as per your requirements
CGRect firstLabelRect = firstLabel.frame;
firstLabelRect.size.width = labelSize.width;
//You will get the width as per the text in label
firstLabel.frame = firstLabelRect;
/* Now, let's change the frame for the second label */
CGRect secondLabelRect;
CGFloat x = firstLabelRect.origin.x;
CGFloat y = firstLabelRect.origin.y;
x = x + labelSize.width + 20; //There are some changes here.
secondLabelRect = secondLabel.frame;
secondLabelRect.origin.x = x;
secondLabelRect.origin.y = y;
secondLabel.frame = secondLabelRect;
The following line is throwing the error, what's the matter with it?
CGSize size = [label
sizeWithStyle:style
forWidth:bounds.size.width];
My code:
MSHook(void, drawRectLabel, SBIconLabel *self, SEL sel, CGRect rect) {
CGRect bounds = [self bounds];
NSString *label(MSHookIvar<NSString *>(self, "_label"));
NSString *style = [NSString stringWithFormat:#"color: white; "];
CGSize size = [label sizeWithStyle:style forWidth:bounds.size.width];
[label drawAtPoint:CGPointMake((bounds.size.width - size.width) / 2, 0) withStyle:style];
}
I'm not familiar with -sizeWithStyle:forWidth:, but my guess is it returns an object, not a CGSize. Perhaps you could post the interface for that category method?