Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel render text incorrectly in IOS7

Tags:

uilabel

ios7

I use following code to calculate the bound of a UILabel

CGRect bound = [lblName.text boundingRectWithSize:(CGSize){206, 99999}
                                    options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                 attributes:stringAttributes
                                          context:nil];

The UILabel is a embedded in a UIScrollView, which is a subview of UITableViewCell.

here what i got

enter image description here

I made a test which use a UILabel in a table cell, and a UILabel in UIScrollView separately, and results are as I expected

enter image description here

Note that all setting (font, line break mode etc) of UILabel are the same in all those case. The boundingRectWithSize returns same result in all those case, only difference is the way UILabel render the text.

What is the problem here? did i miss sometthing?

UPDATE: this happen only when i load UILabel from nib, if it is created programmatically, there is no problem. (my project is migrated from xcode 4 to xcode 5)

like image 341
jAckOdE Avatar asked Sep 25 '13 05:09

jAckOdE


2 Answers

Try this:

bound.size.height += 1;

UPDATE:

According to Apple's document

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context

This method returns fractional sizes (in the size component of the returned CGRect); to use a returned size to size views, you must use raise its value to the nearest higher integer using the ceil function.

So you might want to use this approach:

bound.size.height = ceil(bound.size.height);
like image 99
Tim Chen Avatar answered Nov 06 '22 18:11

Tim Chen


I was seeing the same behavior with some of my labels, which looked fine in iOS 6, but in iOS 7 they had extra padding at the top and bottom as in your pictures.

Here's what I had to do to finally get it to layout correctly in viewDidLoad - works on both iOS 6 and 7.

self.someLabel.autoresizingMask = UIViewAutoresizingNone;
self.someLabel.frame = CGRectMake(
    self.someLabel.frame.origin.x,
    self.someLabel.frame.origin.y,
    labelWidth, // define elsewhere if you're targeting different screen widths
    self.someLabel.bounds.size.height);
[self.someLabel sizeToFit];
like image 22
David Nix Avatar answered Nov 06 '22 20:11

David Nix