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

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

Related

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:

Is there a way to get the text height (point perfect not approximate ) for a UITextview in iOS7 (for a chat cell in tableview ) with constant width?

UITextview has a padding of 8 points on each side. Hence I pass 16 points less to the width of the CGRect- height of which I want to find.
As it can be seen in the below function(using sizeWithFont), for iOS6, I get point perfect height.
But for iOS7, the height I get is not accurate when I use the function (using boundingRectWithSize).
#pragma mark - Private methods
- (CGFloat)getTextHeight{
if (isSentMessgae) {
return [_chatMessageModel.message sizeWithFont:[UIFont fontWithName:FONT_TT size:16] constrainedToSize:CGSizeMake(194, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping].height;
}
return [_chatMessageModel.message sizeWithFont:[UIFont fontWithName:FONT_TT size:16] constrainedToSize:CGSizeMake(154, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping].height;
}
- (CGFloat)getTextHeightIOS7{
if (isSentMessgae) {
NSString *text = _chatMessageModel.message;
CGFloat width =154;
UIFont *font = [UIFont fontWithName:FONT_TT size:16];
if (isSentMessgae) {
width =194;
}
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:text
attributes:#
{
NSFontAttributeName: font
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
DebugLog("text heigh : %f",rect.size.height);
return (rect.size.height);
}
NSString *text = _chatMessageModel.message;
CGFloat width =154;
UIFont *font = [UIFont fontWithName:FONT_TT size:16];
if (isSentMessgae) {
width =194;
}
NSAttributedString *attributedText =
[[NSAttributedString alloc]
initWithString:text
attributes:#
{
NSFontAttributeName: font
}];
CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
// DebugLog("text heigh : %f",rect.size.height);
return (rect.size.height ));
}

Contenting deprecated sizeWithFont:constrainedToSize to boundingRectWithSize:options:attributes:context:

How can I convert
CGSize labelHeighSize = [text sizeWithFont: [UIFont systemFontOfSize:16] constrainedToSize:maximumSize lineBreakMode:NSLineBreakByTruncatingTail];
to
CGSize labelHeighSize = [text boundingRectWithSize:maximumSize options: attributes: context:
First of all the method:
- (CGRect) boundingRectWithSize:(CGSize)size
options:(NSStringDrawingOptions)options
attributes:(NSDictionary *)attributes
context:(NSStringDrawingContext *)context;
returns CGRect not the CGSize so you need to use CGRect.
EDIT
according to apple docs see here, it says
This option is ignored if NSStringDrawingUsesLineFragmentOrigin is not
also set. In addition, the line break mode must be either
NSLineBreakByWordWrapping or NSLineBreakByCharWrapping for this option
to take effect. The line break mode can be specified in a paragraph
style passed in the attributes dictionary argument of the drawing
methods.
Below is the sample code that you can use:
NSString *text = #"Some text to measure";
UIFont *labelFont = [UIFont systemFontOfSize:16];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
//set the line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attrDict = [NSDictionary dictionaryWithObjectsAndKeys:labelFont,
NSFontAttributeName,
paragraphStyle,
NSParagraphStyleAttributeName,
nil];
//assume your maximumSize contains {255, MAXFLOAT}
CGRect lblRect = [text boundingRectWithSize:(CGSize){225, MAXFLOAT}
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attrDict
context:nil];
CGSize labelHeighSize = lblRect.size;

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

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;

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:#“ "];

Resources