我将uilabel子类化,因此它会自行调整大小,但由于某种原因,我的最后一句话被截断为......
大部分时间这个工作都很好,但由于某些原因我的x字符句子被截断,我不明白为什么。有人可以看看这个吗?
- (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;
}
我的句子应该在3行,但它只计算2。
答案 0 :(得分:1)
为了准确计算UILabel的高度,您可以使用sizeWithFont constrainedToSize:lineBreakMode:
例如:
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;
在这种方法中,我们希望用户输入UILabel的宽度,字体和 lineBreakMode ,并返回预期的帧大小。