sizeWithFont:constrainedToSize - iOS7 - ios7

I have the following method that I used in iOS6 but with iOS7 I'm getting errors on
CGSize labelHeight = [tweetText sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(self.tweetsTableView.bounds.size.width - 84, 4000)];
full method below, any ideas on how to amend for iOS7?
- (CGFloat)heightForCellAtIndex:(NSUInteger)index {
NSDictionary *tweet = self.tweets[index];
CGFloat cellHeight = 50;
NSString *tweetText = tweet[#"text"];
CGSize labelHeight = [tweetText sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(self.tweetsTableView.bounds.size.width - 84, 4000)];
cellHeight += labelHeight.height;
return cellHeight;
}

I know this is an old question & late answer, but it's still very relevant,
This sizeWithFont method is now deprecated, this new method works best
NSString *content = **Whatever your label's content is expected to be**
CGSize maximumLabelSize = CGSizeMake(390, 1000);
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName];
CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
So you can adjust your label (or table cell etc) to
label.frame.size.height = newExpectedLabelSize.height;
I hope this helps, cheers, Jim.

Add this lines:
UIFont *font = [UIFont boldSystemFontOfSize:16];
CGRect new = [string boundingRectWithSize:CGSizeMake(200, 300) options:NSStringDrawingUsesFontLeading attributes:#{NSFontAttributeName: font} context:nil];
CGSize stringSize= new.size;

Related

SizeWithFont deprecated in IOS7

How to change
CGSize size=[tempStr sizeWithFont:[UIFont boldSystemFontOfSize:17] constrainedToSize:CGSizeMake(200, 56)];
to make it work with IOS7
You have to use sizeWithAttributes:, using something like:
UIFont *font = [UIFont boldSystemFontOfSize:17.0f];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
CGSize size = [tempStrig sizeWithAttributes:attrDictionary];
CGFloat finalHeight;
CGSize constrainedSize = CGSizeMake(requiredWidth,9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:yourRequiredFont, NSFontAttributeName,nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:yourText attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > requiredWidth) {
requiredHeight = CGRectMake(0,0,requiredWidth, requiredHeight.size.height);
}
finalHeight=requiredHeight.size.height;

UIlabel height issue in Custom UItableViewCell in iOS 6 and iOS 7

i am displaying different items in custom table cell. when i try to display multiline uilabel text. it si only showing single line. even though i calculate the label height
also i try to set new frame with new height after calculation.
my code is as follows:
+(CGRect )getlabelHeight:(CGRect)frame withFontName:(NSString *)font andFontSize:(float)fontSize andText:(NSString *)text
{
CGSize constrainedSize = CGSizeMake(frame.size.width, 9999);
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:font size:fontSize], NSFontAttributeName,
nil];
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:text attributes:attributesDictionary];
CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];
if (requiredHeight.size.width > constrainedSize.width) {
requiredHeight = CGRectMake(0,0, constrainedSize.width, requiredHeight.size.height);
}
CGRect newFrame = frame;
newFrame.size.height = requiredHeight.size.height;
frame = newFrame;
return frame;
}
my tabelview method is as follows:
CGRect descFrame=[Utility getlabelHeight:CGRectMake(65,35+titleFrame.size.height, 250, 20) withFontName:appFont andFontSize:15 andText:[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"]];
NSLog(#"%# \n %f",[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"],descFrame.size.height);
[cell.title setFont:[UIFont fontWithName:appFont size:15]];
[cell.title setText:[[allComments objectAtIndex:indexPath.row]valueForKey:#"comment"]];
[cell.title setLineBreakMode:NSLineBreakByWordWrapping];
[cell.title setNumberOfLines:0];
[cell.title setFrame:descFrame];
[cell.title setTextColor:[UIColor blackColor]];
Please help me!!1 i am screwed...
thanks you!!!

deprecated ’sizeWithFont:constrainedToSize:' replacement

Somebody knows how to use -boundingRectWithSize:options:attributes:context: as a replacement of the deprecated ”sizeWithFont:constrainedToSize:” method in this case.
CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];
Gets the warning: 'sizeWithFont:constrainedToSize:' is deprecated: first deprecated in iOS 7.0 - Use -boundingRectWithSize:options:attributes:context:
This is the hole code piece:
// calculate the label size
CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];
each_object(self.labels, ^(UILabel *label) {
CGRect frame = label.frame;
frame.origin.x = offset;
frame.size.height = CGRectGetHeight(self.bounds);
frame.size.width = labelSize.width + 2.f /*Magic number*/;
label.frame = frame;
// Recenter label vertically within the scroll view
label.center = CGPointMake(label.center.x, roundf(self.center.y - CGRectGetMinY(self.frame)));
offset += CGRectGetWidth(label.bounds) + self.labelSpacing;
});
At the moment you have...
CGSize labelSize = [self.mainLabel.text sizeWithFont:self.mainLabel.font constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))];
So use...
CGRect boundingRect = [self.mainLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
CGSize labelSize = boundingRect.size;
That should work.
Or... with attributes...
CGRect boundingRect = [self.mainLabel.text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.bounds))
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{NSFontAttributeName:self.mainLabel.font}
context:nil];
For example this way
-(CGFloat)getLabelSize:(UILabel *)label fontSize:(NSInteger)fontSize
{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:fontSize], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(270, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
return size.height;
}

sizeWithFont method is deprecated. boundingRectWithSize returns an unexpected value

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.

How to calculate the Width and Height of NSString on UILabel

I am working on a project to make the NSString on UILabel Width and Height dynamically.
I tried with:
NSString *text = [messageInfo objectForKey:#"compiled"];
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
NSLog(#"sizewidth = %f, sizeheight = %f", size.width, size.height);
NSLog(#"writerNameLabel.frame.size.width 1 -> %f",writerNameLabel.frame.size.width);
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
CGRect labelFram = writerNameLabel.frame;
labelFram.origin.x = cell.frame.size.width - writerNameLabel.frame.size.width - 80;
writerNameLabel.frame = labelFram;
NSLog(#"writerNameLabel.frame.size.width 2-> %f",writerNameLabel.frame.size.width);
Please see the green bubble not the grey one.
Still not right.
The code for bubble
bubbleImageView.frame = CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, writerNameLabel.frame.size.width+15, writerNameLabel.frame.size.height+5);
Please Advise! Thanks!
That's because you did not reuse the table cell, the structure should be like:
NSString *text = [messageInfo objectForKey:#"compiled"];
if(cell == nil)
{
writerNameLabel.numberOfLines = 0;
writerNameLabel.textAlignment = UITextAlignmentRight;
writerNameLabel.backgroundColor = [UIColor clearColor];
[cell addSubview:writerNameLabel];
}
else {
writerNameLabel = (UILabel *)[cell viewWithTag:WRITER_NAME_LABEL_TAG];
}
CGSize constraint = CGSizeMake(296,9999);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE]
constrainedToSize:constraint
lineBreakMode:UILineBreakModeWordWrap];
[writerNameLabel setFrame:CGRectMake(writerNameLabel.frame.origin.x, writerNameLabel.frame.origin.y, size.width, size.height)];
I've been gone through and answered some of your question, that's correct way to write your tableview controller. And your problem will be solved.