我找到了许多带有“adjustsFontSizeToFitWidth
”属性的解决方案,但这些解决方案都不适用于IOS8。
我开发了一个自适应应用,标签字体大小必须根据屏幕宽度进行更改...
我有:
label = [[UILabel alloc] init];
label.numberOfLines = 1;
label.adjustsFontSizeToFitWidth = YES;
label.font = [UIFont fontWithName:FONT_DIGITAL size:60];
[label setMinimumScaleFactor:8.0/label.font.pointSize];
label.textAlignment = NSTextAlignmentCenter;
label.frame = CGRectMake(0, 0, self.width, self.height);
label.text = @"TEXT";
[self addSubview:valueLabel];
有人有解决方案吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
以下答案是一个黑客(不是最好的解决方案),但它有效,所以如果你想,你可以尝试:
- (void) sizeLabel: (UILabel *) label toRect: (CGRect) labelRect {
// Set the frame of the label to the targeted rectangle
label.frame = labelRect;
// Try all font sizes from largest to smallest font size
CGFloat fontSize = 16.0f;
CGFloat minFontSize = 5.0f;
// Fit label width wize
CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);
do {
// Set current font size
label.font = [UIFont fontWithName:label.font.fontName size:fontSize];
// Find label size for current font size
CGRect textRect = [[label text] boundingRectWithSize:constraintSize
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:label.font}
context:nil];
CGSize labelSize = textRect.size;
// Done, if created label is within target size
if( labelSize.height <= label.frame.size.height )
break;
// Decrease the font size and try again
fontSize -= 1.0f;
} while (fontSize > minFontSize);
}