[英]Shrink text inside UIlabel programmatically
我正在嘗試在UILabel中縮小文本。 我的文本是一個字符串,我最多只能有7行,有時還不夠,那么我需要縮小文本以適合這7行。 這是我的代碼。
// create label
UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(5, 220, 310, 200)];
desc.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
desc.font = [UIFont fontWithName:@"Helvetica" size:30];
desc.numberOfLines = 7;
desc.textColor = [UIColor blackColor];
desc.layer.borderColor = [UIColor blackColor].CGColor;
desc.layer.borderWidth = 1.0;
desc.text = // MY string ;
desc.adjustsFontSizeToFitWidth = YES;
[self.view addSubview:desc];`
我什至嘗試了[desc sizeToFit]
;
我無法弄清楚我在做什么錯。 我已經檢查了有關此的所有帖子。
謝謝你的幫助
您可以使用輔助函數來調整其大小。 這是一個例子。 我只是將lineBreakMode更改為NSLineBreakByWordWrapping(因為iOS6中已棄用以前的版本)。
+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize
{
// use font from provided label so we don't lose color, style, etc
UIFont *font = aLabel.font;
// start with maxSize and keep reducing until it doesn't clip
for(int i = maxSize; i > 10; i--) {
font = [font fontWithSize:i];
CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);
// This step checks how tall the label would be with the desired font.
CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
if(labelSize.height <= aLabel.frame.size.height)
break;
}
// Set the UILabel's font to the newly adjusted font.
aLabel.font = font;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.