使用 UILabel 的 sizeToFit 而不是 sizeWithFont: 来布局多行 UILabel,因为 sizeWithFont: 会截断字符串(参见苹果文档)。以下代码会减小标签的字体大小,直到文本适合指定的大小...一旦适合指定的高度,就会使用多行文本:
-(void)setFontSizeOfMultiLineLabel: (UILabel*)label
toFitSize: (CGSize) size
forMaxFontSize: (CGFloat) maxFontSize
andMinFontSize: (CGFloat) minFontSize
startCharacterWrapAtSize: (CGFloat)characterWrapSize{
CGRect constraintSize = CGRectMake(0, 0, size.width, 0);
label.frame = constraintSize;
label.lineBreakMode = UILineBreakModeWordWrap;
label.numberOfLines = 0; // allow any number of lines
for (int i = maxFontSize; i > minFontSize; i--) {
if((i < characterWrapSize) && (label.lineBreakMode == UILineBreakModeWordWrap)){
// start over again with lineBreakeMode set to character wrap
i = maxFontSize;
label.lineBreakMode = UILineBreakModeCharacterWrap;
}
label.font = [label.font fontWithSize:i];
[label sizeToFit];
if(label.frame.size.height < size.height){
break;
}
label.frame = constraintSize;
}
}
使用具有您喜欢的文本和字体的标签调用它:
UILabel *label = [[UILabel alloc] initWithFrame: CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.textColor = [UIColor whiteColor];
label.text = text;
label.font = [UIFont fontWithName: @"Helvetica" size: 16];
[self setFontSizeOfMultiLineLabel: label toFitSize: CGSizeMake(200, 44) forMaxFontSize: 16 andMinFontSize: 8 startCharacterWrapAtSize: 11];
startCharacterWrapAtSize 参数允许您选择从给定字体大小开始使用 characterWrap。如果 wordWrap 使用非常小的字体,这应该可以节省空间。
编辑:错误修正