Reputation: 5077
I subclassed the uilabel so it would resize itself but for some reason my last word is being truncated to ...
Most of the time this works just fine but for some reason my sentence with x characters gets truncated and I dont understand why. Could somebody take a look at this?
- (void)setFrame:(CGRect)newFrame {
NSInteger maxNrOfLines = maxNumberOfLines == 0 ? 9999 : maxNumberOfLines;
NSString *text = self.text;
UIFont *font = self.font;
CGSize lineSize = CGSizeMake(newFrame.size.width, maxNrOfLines * font.lineHeight);
CGSize size = [text sizeWithFont:font constrainedToSize:lineSize lineBreakMode:self.lineBreakMode];
NSInteger lineCount = MIN(maxNrOfLines, MAX(1, size.height / font.lineHeight));
CGFloat height = font.lineHeight * lineCount + 10;
newFrame.size.height = height;
super.frame = newFrame;
super.numberOfLines = newFrame.size.height / font.lineHeight;
}
My sentence should be on 3 lines but it calculates only 2.
Upvotes: 0
Views: 3045
Reputation: 706
In order to calculate height of UILabel accurately, you can use sizeWithFont constrainedToSize:lineBreakMode:
Example:
float width = 296;
CGSize maximumLabelSize = CGSizeMake(width, 9999);
CGSize expectedLabelSize = [yourText sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];
//set height of yourLabel to what we calculated
CGRect frame = yourLabel.frame;
frame.size.height = expectedLabelSize.height;
yourLabel.frame = frame;
In this approach, we expect user to input width, font and lineBreakMode of UILabel and it returns expected frame size.
Upvotes: 1