sizeWithFont: ConstrainedToSize: lineBreakMode: method is deprecated in iOS 7 - ios

sizeWithFont: ConstrainedToSize: lineBreakMode: method is deprecated in iOS 7 and I'm a little unsure how to handle this exactly. After a little of research on the internet I found that there's a new method for handling this, which is:
[txt drawWithRect: options: attributes: context:]
This is the method that I am currently attempting to run:
+ (CGSize)textSizeForText:(NSString *)txt
{
CGFloat width = [UIScreen mainScreen].applicationFrame.size.width * 0.75f;
CGFloat height = MAX([JSBubbleView numberOfLinesForMessage:txt],
[txt numberOfLines]) * [JSMessageInputView textViewLineHeight];
return [txt sizeWithFont:[JSBubbleView font]
constrainedToSize:CGSizeMake(width - kJSAvatarSize, height + kJSAvatarSize)
lineBreakMode:NSLineBreakByWordWrapping];
}
But I'm having a hard time converting it to the new method. Mainly with the lineBreakMode: which is nowhere in the new method. Any ideas?

in the new method, for line break, you have to create a NSMutableParagraphStyle Style first:
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
Then simply use the new method by passing all the necessary parameters
CGRect textRect = [text boundingRectWithSize:CGSizeMake(width - kJSAvatarSize, height + kJSAvatarSize)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSParagraphStyleAttributeName: paragraphStyle.copy}
context:nil];
return textRect.size;
if you want this to be tide, you can do
return ([text boundingRectWithSize:CGSizeMake(width - kJSAvatarSize, height + kJSAvatarSize)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSParagraphStyleAttributeName: paragraphStyle.copy}
context:nil]).size;
Hope that helps
I will add the font attributes in above answer
return ([text boundingRectWithSize:CGSizeMake(width - kJSAvatarSize, height + kJSAvatarSize)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSParagraphStyleAttributeName: paragraphStyle.copy, NSFontAttributeName:[UIFont fontWithName:#"HelveticaNeue" size:14]}
context:nil]).size;

Related

SGABRT error on depricated code in iOS xcode [duplicate]

In iOS7, sizeWithFont is deprecated, so I am using boundingRectWithSize(which returns a CGRect value). My code:
UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.
CGSize maximumLabelSize = CGSizeMake(310, 9999);
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:fontText}
context:nil];
expectedLabelSize = CGSizeMake(textRect.size.width, textRect.size.height);
In textRect, I'm getting a size greater than my maximumLabelSize, a different size than when using sizeWithFont. How can I resolve this issue?
How about create new label and using sizeThatFit:(CGSize)size ??
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:#"YOUR FONT's NAME" size:16];
gettingSizeLabel.text = #"YOUR LABEL's TEXT";
gettingSizeLabel.numberOfLines = 0;
gettingSizeLabel.lineBreakMode = NSLineBreakByWordWrapping;
CGSize maximumLabelSize = CGSizeMake(310, CGFLOAT_MAX);
CGSize expectSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
Edit: This upper code is not good for ios 7 and above, so please use below:
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:NSStringDrawingUsesLineFragmentOrigin| NSStringDrawingUsesFontLeading
attributes:#{NSFontAttributeName:fontText}
context:nil];
Maybe you need to provide additional option to the method that is suggested in this answer:
CGSize maximumLabelSize = CGSizeMake(310, CGFLOAT_MAX);
CGRect textRect = [myString boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName: fontText}
context:nil];
Here is my working code snippet:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:attributeDict];
NSString *headline = [dict objectForKey:#"title"];
UIFont *font = [UIFont boldSystemFontOfSize:18];
CGRect rect = [headline boundingRectWithSize:CGSizeMake(300, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName:font} context:nil];
CGFloat height = roundf(rect.size.height +4)
I added 4px to the calculated height, because without these 4px, there is one line missing.
I use this code snippet in a tableView and add the "height" to an array of NSNumbers and I get the correct cell height for the default textLabel.
Add 4 more pixel if you want more space under the text in the textLabel.
**** UPDATE ****
I do not agree with the "width bug of 40px", I shout be the 4px of missing height, because 4px is the default height of a space between a letter and the bound of a single line.
You can check it with a UILabel, for a fontsize of 16 you need a UILabel height of 20.
But if your last line has no "g" or whatever in it, the measuring could be miss the 4px of height.
I rechecked it with a little method, I get an accurate height of 20,40 or 60
for my label and a right width less than 300px.
To support iOS6 and iOS7, you can use my method:
- (CGFloat)heightFromString:(NSString*)text withFont:(UIFont*)font constraintToWidth:(CGFloat)width
{
CGRect rect;
float iosVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
if (iosVersion >= 7.0) {
rect = [text boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName:font} context:nil];
}
else {
CGSize size = [text sizeWithFont:font constrainedToSize:CGSizeMake(width, 1000) lineBreakMode:NSLineBreakByWordWrapping];
rect = CGRectMake(0, 0, size.width, size.height);
}
NSLog(#"%#: W: %.f, H: %.f", self, rect.size.width, rect.size.height);
return rect.size.height;
}
**** UPGRADE ****
Thanks to your comments, I upgraded my function as followed. Since sizeWithFont is deprecated and you will get a warning in XCode, I added the diagnostic-pragma-code to remove the warning for this particular function-call/block of code.
- (CGFloat)heightFromStringWithFont:(UIFont*)font constraintToWidth:(CGFloat)width
{
CGRect rect;
if ([self respondsToSelector:#selector(boundingRectWithSize:options:attributes:context:)]) {
rect = [self boundingRectWithSize:CGSizeMake(width, 1000) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName:font} context:nil];
}
else {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
CGSize size = [self sizeWithFont:font constrainedToSize:CGSizeMake(width, 1000) lineBreakMode:NSLineBreakByWordWrapping];
rect = CGRectMake(0, 0, size.width, size.height);
#pragma GCC diagnostic pop
}
return ceil(rect.size.height);
}
In addition to the 4px topic:
depending which font and font-weight you use, the calculation returns different height-values. In my case: HelveticaNeue-Medium with a fontsize of 16.0 returns a line-height of 20.0 for a single line but 39.0 for two lines, 78px for 4 lines --> 1px missing for every line - beginning with line 2 - but you want to have your fontsize + 4px linespace for every line you have to get a height-result.
Please keep that in mind while coding!
I don´t have a function yet for this "problem" but I will update this post when I´m finished.
If I understand correctly, you are using boundingRectWithSize: just as a way of getting the size you would get with sizeWithFont (meaning you want directly the CGSize, not the CGRect)?
This looks like what you are looking for :
Replacement for deprecated sizeWithFont: in iOS 7?
They are using sizeWithAttributes: to get the size, as a replacement for sizeWithFont.
Do you still get the wrong size using something like this :
UIFont *fontText = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16];
// you can use your font.
expectedLabelSize = [myString sizeWithAttributes:#{NSFontAttributeName:fontText}];
The #SoftDesigner's comment has worked for me
CGRect descriptionRect = [description boundingRectWithSize:CGSizeMake(width, 0)
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:#{NSFontAttributeName : [UIFont systemFontOfSize:12]}
context:nil];
result = ceil(descriptionRect.size.height);
for finding size of label run time sizewithfont is deprecated for iOS 7.0 instead of that you have to use -boundingRectWithSize:options:attributes:context: method
you can use it like below code
CGSize constraint = CGSizeMake(MAXIMUM_WIDHT, TEMP_HEIGHT);
NSRange range = NSMakeRange(0, [[self.message body] length]);
NSDictionary *attributes = [YOUR_LABEL.attributedText attributesAtIndex:0 effectiveRange:&range];
CGSize boundingBox = [myString boundingRectWithSize:constraint options:NSStringDrawingUsesFontLeading attributes:attributes context:nil].size;
int numberOfLine = ceil((boundingBox.width) / YOUR_LABEL.frame.size.width);
CGSize descSize = CGSizeMake(ceil(boundingBox.width), ceil(self.lblMessageDetail.frame.size.height*numberOfLine));
CGRect frame=YOUR_LABEL.frame;
frame.size.height=descSize.height;
YOUR_LABEL.frame=frame;
here you have to give width to maximum length for finding height or width.
try this it is working for me.

Setting dynamic UILabel Height

I have an app with a table view that needs to support dynamic cell heights. In the cell's layoutSubviews method, I am generating a frame for my UILabel controls, which are the only dynamic sized controls in the cells.
For some reason, the width being returned from the following method is less than what it should be and the text gets truncated, but only on short text, such as one word. The width should be maintained as the width that is passed in as the initial frame.
That said, what my method needs to accomplish is adjusting the size of the label to fit all the text while maintaining a preset width.
Here's the code I am using:
- (CGRect)getLabelSizeForText:(NSString*)text withInitialRect:(CGRect)labelFrame andFontSize:(CGFloat)fontSize{
CGSize constrainedSize = CGSizeMake(labelFrame.size.width, MAXFLOAT);
NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:fontSize], NSFontAttributeName, nil];
CGSize requiredSize = [text boundingRectWithSize:constrainedSize
options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
attributes:attributesDict context:nil].size;
CGRect adjustedFrameRect = CGRectMake(labelFrame.origin.x, labelFrame.origin.y, requiredSize.width, requiredSize.height);
return adjustedFrameRect;
}
This works for me,
+ (CGSize)textSizeForText:(NSString *)text {
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat width = screenWidth - kPaddingRight;
CGSize maxSize = CGSizeMake(width, CGFLOAT_MAX);
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 2.5;
NSDictionary *dict = #{NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName: [UIFont systemFontOfSize:15] };
[attributedString addAttributes:dict range:NSMakeRange(0, text.length)];
CGRect paragraphRect = [attributedString boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) context:nil];
return paragraphRect.size;
}

Lost with the replacement for deprecated sizeWithFont: in iOS 7

I have a warning that sizeWithFont: is deprecated, i have try to replace it to sizeWithAttributes: but everything i try is not working.
The code is supposed to tell me the expected size of a UILabel and the cCell is the cell and the label fro the IB.
Thanks for all your help.
CGSize maximumLabelSize = CGSizeMake(210, FLT_MAX);
expectedLabelSize = [labelText sizeWithFont:cCell.lblHotelResponse.font constrainedToSize:maximumLabelSize lineBreakMode:cCell.lblHotelResponse.lineBreakMode];
You need to use sizeWithAttributes: instead.
NSDictionary *attributeDict = #{NSFontAttributeName:cCell.lblHotelResponse.font};
CGSize expectedLabelSize = [labelText sizeWithAttributes:attributeDict];
Another way is:
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:labelText attributes:#{NSFontAttributeName: cCell.lblHotelResponse.font}];
CGRect rect = [attributedString boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
CGSize labelSize = rect.size;
References:
sizeWithAttributes:
boundingRectWithSize:options:attributes:

iOS 7 uitextview NSLineBreakByWordWrapping not working

In iOS 7 I use new method to calculate the textview height,but it seems that it's not word wrapping, besides,the height is not the height of the text.
self.textview.textContainer.lineBreakMode = NSLineBreakByWordWrapping;
self.textview.showsHorizontalScrollIndicator= NO;
self.textview.showsVerticalScrollIndicator = NO;
// [self.textview sizeThatFits:CGSizeMake(296, 474)];
// [self.textview.text sizeWithFont:[UIFont systemFontOfSize:14] forWidth:296.0 lineBreakMode:NSLineBreakByWordWrapping];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
NSDictionary *attributes = #{ NSFontAttributeName: self.textview.font, NSParagraphStyleAttributeName : paragraphStyle };
//
CGSize size= [self.textview.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.textview.frame), MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil].size;
CGRect frame = self.textview.frame;
frame.size = size;
self.textview.frame= frame;
anyone help?
solved the problem it's because the text has wrong white charter ,that is it replace white character with other character.
Try this:
CGSize maximumLabelSize = CGSizeMake(295,99999);
CGSize expectedLabelSize = [self.textview. sizeWithFont:self.textview..font constrainedToSize:maximumLabelSize lineBreakMode:self.textview.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = self.textview.frame;
newFrame.size.height = expectedLabelSize.height;
self.textview.frame = newFrame;
Check image having your given text : http://screencast.com/t/Yqr6oSOvhN1
I had a similar problem because I had a wrong character space.
For replace I used:
message = [message stringByReplacingOccurrencesOfString:#"\u00A0" withString:#“ "];

Replacement for deprecated -sizeWithFont:constrainedToSize:lineBreakMode: in iOS 7?

In iOS 7, the method:
- (CGSize)sizeWithFont:(UIFont *)font
constrainedToSize:(CGSize)size
lineBreakMode:(NSLineBreakMode)lineBreakMode
and the method:
- (CGSize)sizeWithFont:(UIFont *)font
are deprecated. How can I replace
CGSize size = [string sizeWithFont:font
constrainedToSize:constrainSize
lineBreakMode:NSLineBreakByWordWrapping];
and:
CGSize size = [string sizeWithFont:font];
You could try this:
CGRect textRect = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:FONT}
context:nil];
CGSize size = textRect.size;
Just change "FONT" for an "[UIFont font....]"
As we cant use sizeWithAttributes for all iOS greater than 4.3 we have to write conditional code for 7.0 and previous iOS.
1) Solution 1:
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(#"7.0")) {
CGSize size = CGSizeMake(230,9999);
CGRect textRect = [specialityObj.name
boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:[UIFont fontWithName:[AppHandlers zHandler].fontName size:14]}
context:nil];
total_height = total_height + textRect.size.height;
}
else {
CGSize maximumLabelSize = CGSizeMake(230,9999);
expectedLabelSize = [specialityObj.name sizeWithFont:[UIFont fontWithName:[AppHandlers zHandler].fontName size:14] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap]; //iOS 6 and previous.
total_height = total_height + expectedLabelSize.height;
}
2) Solution 2
UILabel *gettingSizeLabel = [[UILabel alloc] init];
gettingSizeLabel.font = [UIFont fontWithName:[AppHandlers zHandler].fontName size:16]; // Your Font-style whatever you want to use.
gettingSizeLabel.text = #"YOUR TEXT HERE";
gettingSizeLabel.numberOfLines = 0;
CGSize maximumLabelSize = CGSizeMake(310, 9999); // this width will be as per your requirement
CGSize expectedSize = [gettingSizeLabel sizeThatFits:maximumLabelSize];
The first solution is sometime fail to return proper value of height. so use another solution. which will work perfectly.
The second option is quite well and working smoothly in all iOS without conditional code.
Here is simple solution :
Requirements :
CGSize maximumSize = CGSizeMake(widthHere, MAXFLOAT);
UIFont *font = [UIFont systemFontOfSize:sizeHere];
Now As constrainedToSizeusage:lineBreakMode: usage is deprecated in iOS 7.0:
CGSize expectedSize = [stringHere sizeWithFont:font constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
Now usage in greater version of iOS 7.0 will be:
// Let's make an NSAttributedString first
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:stringHere];
//Add LineBreakMode
NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
[attributedString setAttributes:#{NSParagraphStyleAttributeName:paragraphStyle} range:NSMakeRange(0, attributedString.length)];
// Add Font
[attributedString setAttributes:#{NSFontAttributeName:font} range:NSMakeRange(0, attributedString.length)];
//Now let's make the Bounding Rect
CGSize expectedSize = [attributedString boundingRectWithSize:maximumSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
Below are two simple methods that will replace these two deprecated methods.
And here are the relevant references:
If you are using NSLineBreakByWordWrapping, you don't need to specify the NSParagraphStyle, as that is the default:
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSParagraphStyle_Class/index.html#//apple_ref/occ/clm/NSParagraphStyle/defaultParagraphStyle
You must get the ceil of the size, to match the deprecated methods' results.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/NSString_UIKit_Additions/#//apple_ref/occ/instm/NSString/boundingRectWithSize:options:attributes:context:
+ (CGSize)text:(NSString*)text sizeWithFont:(UIFont*)font {
CGSize size = [text sizeWithAttributes:#{NSFontAttributeName: font}];
return CGSizeMake(ceilf(size.width), ceilf(size.height));
}
+ (CGSize)text:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size{
CGRect textRect = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName: font}
context:nil];
return CGSizeMake(ceilf(textRect.size.width), ceilf(textRect.size.height));
}
In most cases I used the method sizeWithFont:constrainedToSize:lineBreakMode: to estimate the minimum size for a UILabel to accomodate its text (especially when the label has to be placed inside a UITableViewCell)...
...If this is exactly your situation you can simpy use the method:
CGSize size = [myLabel textRectForBounds:myLabel.frame limitedToNumberOfLines:mylabel.numberOfLines].size;
Hope this might help.
UIFont *font = [UIFont boldSystemFontOfSize:16];
CGRect new = [string boundingRectWithSize:CGSizeMake(200, 300) options:NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName: font} context:nil];
CGSize stringSize= new.size;
[Accepted answer works nicely in a category. I'm overwriting the deprecated method names. Is this a good idea? Seems to work with no complaints in Xcode 6.x]
This works if your Deployment Target is 7.0 or greater. Category is NSString (Util)
NSString+Util.h
- (CGSize)sizeWithFont:(UIFont *) font;
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size;
NSString+Util.m
- (CGSize)sizeWithFont:(UIFont *) font {
NSDictionary *fontAsAttributes = #{NSFontAttributeName:font};
return [self sizeWithAttributes:fontAsAttributes];
}
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size {
NSDictionary *fontAsAttributes = #{NSFontAttributeName:font};
CGRect retVal = [self boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:fontAsAttributes context:nil];
return retVal.size;
}
UIFont *font = [UIFont fontWithName:#"Courier" size:16.0f];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
paragraphStyle.alignment = NSTextAlignmentRight;
NSDictionary *attributes = #{ NSFontAttributeName: font,
NSParagraphStyleAttributeName: paragraphStyle };
CGRect textRect = [text boundingRectWithSize:size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributes
context:nil];
CGSize size = textRect.size;
from two answers 1 + 2

Resources