UILabel自适应宽高,实现内部字体自动改变大小,使内容全部显示
- (void)setFontSizeThatFits:(UILabel*)label
{
CGFloat fontSizeThatFits;
[label.text sizeWithFont:label.font
minFontSize:12.0 //最小字体
actualFontSize:&fontSizeThatFits
forWidth:label.bounds.size.width
lineBreakMode:NSLineBreakByWordWrapping];
label.font = [label.font fontWithSize:fontSizeThatFits];
}
还有一种方法 label.adjustsFontSizeToFitWidth = YES; 这一句话就可以了
adjustsFontSizeToFitWidth 实现原理:
self.label1.text = @"1234567890qwertyuiopasdfghjklzxcvbnm"; self.label1.font = [self adjustsFontSize:self.label1];
- (UIFont*)adjustsFontSize:(UILabel*)label{
float curFontSize = label.font.pointSize;
UIFont *font = label.font;
CGRect rect;
rect = [label bounds];
if (rect.size.width == 0.0f || rect.size.height == 0.0f) {
return 0;
}
while (curFontSize > label.minimumScaleFactor && curFontSize > 0.0f) {
CGSize size = CGSizeZero;
// A single line of text should be clipped
if (label.numberOfLines == 1) {
size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByClipping];
// size = [label.text boundingRectWithSize:CGSizeMake(rect.size.width, 0.0f)
// options:NSStringDrawingUsesFontLeading
// attributes:@{NSFontAttributeName: _font}
// context:NULL].size;
} else {
//Multiple lines of text should be wrapped
size = [label.text sizeWithFont:font constrainedToSize:CGSizeMake(rect.size.width, 0.0f) lineBreakMode:NSLineBreakByWordWrapping];
}
if (size.width < rect.size.width && size.height <= rect.size.height) {
break;
}
curFontSize -= 1.0f;
font = [font fontWithSize:curFontSize];
}
if (curFontSize < label.minimumScaleFactor) {
curFontSize = label.minimumScaleFactor;
}
if (curFontSize < 0.0f) {
curFontSize = 1.0f;
}
font = [font fontWithSize:curFontSize];
return font;
}
转载请注明:天狐博客 » UILabel固定尺寸, 自适应字体大小