Sử dụng kích thước của UILabelToFit thay vì sizeWithFont: để bố cục UILabel nhiều dòng, vì sizeWithFont: sẽ cắt ngắn chuỗi (xem tài liệu của apple). Các mã sau đây làm giảm kích thước phông chữ của một nhãn cho đến khi các văn bản phù hợp vào một kích thước quy định ... nhiều dòng văn bản sẽ được sử dụng ngay sau khi họ phù hợp với chiều cao quy định:
-(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;
}
}
Gọi này với một nhãn có văn bản và phông chữ yêu thích của bạn:
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];
Tham số startCharacterWrapAtSize cho phép bạn chọn sử dụng characterWrap bắt đầu từ kích thước phông chữ cho. Điều này sẽ tiết kiệm không gian trong trường hợp wordWrap sẽ sử dụng phông chữ thực sự nhỏ.
chỉnh sửa: bugfix
sizeWithFont không được dùng trong iOS7 và boundingRectWithSize nên được sử dụng thay thế. –