我正在尝试缩小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]
;
我无法弄清楚我做错了什么。我已经检查了所有关于此的帖子。
感谢您的帮助
答案 0 :(得分:1)
您可以使用辅助函数来调整它的大小。 Here就是一个例子。我只是将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;
}
答案 1 :(得分:0)