Reputation: 6973
sizeWithFont:constrainedToSize:lineBreakMode:
don't seem to be returning me the correct width. After these codes are executed, I see that part of the string in the label is chopping off, which means I've to manually add a few pixels to the size. Am I missing something?
I've a UILabel:
theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, LABELWIDTH, LABELHEIGHT)];
theLabel.lineBreakMode = UILineBreakModeWordWrap;
theLabel.numberOfLines = 0;
[theLabel setFont:[UIFont fontWithName:@"MarkerFelt-Wide" size:16]];
theLabel.textColor = [UIColor blackColor];
theLabel.textAlignment = UITextAlignmentLeft;
theLabel.backgroundColor = [UIColor clearColor];
I tried to programmatically modify the size of the label using the following:
CGSize maximumLabelSize = CGSizeMake(LABELWIDTH, 10000);
CGSize expectedLabelSize = [someString sizeWithFont:theLabel.font constrainedToSize:maximumLabelSize lineBreakMode:theLabel.lineBreakMode];
theLabel.text = someString;
CGRect newFrame = theLabel.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = newFrame.size.width+50;
theLabel.frame = newFrame;
Upvotes: 3
Views: 1497
Reputation: 3103
Ok, well, the first thing I'll say is that there are some very useful ways to deal with frames that you currently aren't employing. For example, your code,
CGRect newFrame = theLabel.frame;
newFrame.size.height = expectedLabelSize.height;
newFrame.size.width = newFrame.size.width+50;
theLabel.frame = newFrame;
Can be rewritten with functions from CGGeometry,
CGFloat widthOffset = 50.0f;
theLabel.frame = CGRectOffset(CGRectInset(theLabel.frame, widthOffset, 0.0f), widthOffset / 2.0f, 0.0f);
However, if your code worked as it was intended, you would not need to do this at all. You can go two routes,
[theLabel sizeToFit];
Or, this should also work,
theLabel.frame = CGRectMake(theLabel.frame.origin.x, theLabel.frame.origin.y, expectedLabelSize.width, expectedLabelSize.height);
No where in your earlier code did you change the width of theLabel to match the expected width. Notice, you wrote newFrame.size.width = newFrame.size.width+50
and that should be newFrame.size.width = expectedLabelSize.width
.
Upvotes: 1