I am trying to size a UILabel to fit the bounds of an NSString, but I'm seeing differing results in iOS 7.0.3 and iOS 7.1.1. As you can see below, iOS 7.0.3 doesn't seem to draw the text correctly.
Example 1: The text is drawn toward the bottom of the label, and almost outside of the bounds:
Example 2: The text is drawn on 1 line (instead of 2), and no word wrapping occurs, only tail truncation.
Here's the code that I am using for both versions of iOS listed above.
CGSize boundingSize = CGSizeMake(214, 9999);
CGRect boundingRect = CGRectZero;
[self.nameLabel setNumberOfLines:2];
// for iOS7
if([self.place.placeName respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)]){
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];
boundingRect = [self.place.placeName boundingRectWithSize:boundingSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:[NSDictionary dictionaryWithObjectsAndKeys:
self.nameLabel.font, NSFontAttributeName,
paragraphStyle, NSParagraphStyleAttributeName, nil]
context:nil];
}else{
// pre iOS7
CGSize size = [self.place.placeName sizeWithFont:self.nameLabel.font constrainedToSize:boundingSize lineBreakMode:NSLineBreakByWordWrapping];
boundingRect = CGRectMake(0, 0, size.width, size.height);
}
[self.nameLabel setFrame:CGRectMake(CGRectGetMaxX(self.photoImageView.frame)+15,
CGRectGetMinY(self.photoImageView.frame),
boundingRect.size.width, boundingRect.size.height)];
[self.nameLabel setText:[place placeName]];
Any ideas? Thanks in advance.
I've contacted Apple regarding this issue and they have confirmed it is a bug with iOS 7.0.3, which has been fixed in iOS 7.1.1.
The workaround for the issue (I used to use) is to create your own UILabel subclass, override the - (void)drawTextInRect: method, and use NSString’s - (void)drawInRect:withAttributes: to render the string. (Apple Developer)