UILabel render text incorrectly in IOS7

不羁岁月 提交于 2020-01-31 12:31:05

问题


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

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

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)


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/18996771/uilabel-render-text-incorrectly-in-ios7

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!