扩展费兰的答案
扩展以填充宽度或高度,以先命中者为准
斯威夫特版本
func getFontSizeToFitFrameOfLabel(label: UILabel) -> CGFloat
{
var initialSize : CGSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])
if initialSize.width > label.frame.size.width ||
initialSize.height > label.frame.size.height
{
while initialSize.width > label.frame.size.width ||
initialSize.height > label.frame.size.height
{
label.font = label.font.fontWithSize(label.font.pointSize - 1)
initialSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])
}
} else {
while initialSize.width < label.frame.size.width &&
initialSize.height < label.frame.size.height
{
label.font = label.font.fontWithSize(label.font.pointSize + 1)
initialSize = label.text!.sizeWithAttributes([NSFontAttributeName : label.font])
}
// went 1 point too large so compensate here
label.font = label.font.fontWithSize(label.font.pointSize - 1)
}
return label.font.pointSize;
}
然后做这样的事情来使用它(比如你的标签名为title1Label)
title1Label.frame = CGRect(x: 0.0, y: 0.0, width: view.frame.size.width, height: view.frame.size.height)
// sets font to some nonzero size to begin with, it will change up or down to fit the label's frame
title1Label.font = UIFont(name: "Super Mario 256", size: 45.0)
title1Label.font = title1Label.font.fontWithSize(getFontSizeToFitFrameOfLabel(title1Label))
// resize height to be a little larger than the font height
title1Label.frame.size.height = title1Label.font.pointSize*1.3
目标 C 版本:
- (CGFloat) maxFontSize:(UILabel *)label{
CGSize initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
if (initialSize.width > label.frame.size.width ||
initialSize.height > label.frame.size.height)
{
while (initialSize.width > label.frame.size.width ||
initialSize.height > label.frame.size.height)
{
[label setFont:[label.font fontWithSize:label.font.pointSize - 1]];
initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
}
} else {
while (initialSize.width < label.frame.size.width &&
initialSize.height < label.frame.size.height)
{
[label setFont:[label.font fontWithSize:label.font.pointSize + 1]];
initialSize = [label.text sizeWithAttributes:@{NSFontAttributeName:label.font}];
}
// went 1 point too large so compensate here
[label setFont:[label.font fontWithSize:label.font.pointSize - 1]];
}
return label.font.pointSize;
}