Reputation: 8219
I am programming an iPhone app, in which I am creating a UILabel with dynamic content at runtime. I have no control of the content of UILabel and therefore I have to calculate its size so I can later use those size values to setup some UI constrains.
I am using the following code to create the UILabel and calculate its expected size:
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.font = [UIFont fontWithName:@"Arial-Bold" size:20];
titleLabel.numberOfLines = 0;
titleLabel.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer vulputate venenatis justo in ultrices. Pellentesque eu pharetra elit, id faucibus mi.";
//Calculate the expected lable size
CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
CGFloat contentWidth = applicationFrame.size.width - 20; // 20 is 10+10, a margin of 10 from each side
CGSize maximumLabelSize = CGSizeMake(contentWidth, FLT_MAX); // FLT_MAX here simply means max possible height
CGRect expectedLabelSize = [titleLabel.text boundingRectWithSize:maximumLabelSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:@{
NSFontAttributeName:titleLabel.font
}
context:nil];
When I run the code above, the value expectedLabelSize.size.width
is sometimes larger than the original contentWidth
value passed into boundingRectWithSize:options:attributes:context:
. How do I make sure that contentWidth
is the max width? This is important, because I am using those values in certain constraints later, and it is important that this max width stays the same.
Thanks.
Upvotes: 2
Views: 540
Reputation: 2056
In the Apple's reference, there is an interesting discussion:
This method returns the actual bounds of the glyphs in the string. Some of the glyphs (spaces, for example) are allowed to overlap the layout constraints specified by the size passed in, so in some cases the width value of the size component of the returned CGRect can exceed the width value of the size parameter.
That should be what your are looking for. Is the result width a lot bigger than the "maximum" you are giving? If not I guess the discussion answer you.
Upvotes: 1