jAckOdE
jAckOdE

Reputation: 2500

UILabel render text incorrectly in 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)

Upvotes: 5

Views: 8178

Answers (2)

David Nix
David Nix

Reputation: 3334

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];

Upvotes: 10

Tim Chen
Tim Chen

Reputation: 1382

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);

Upvotes: 16

Related Questions