Here's a function I made to get the adjusted font size of a UILabel:
Swift
func getApproximateAdjustedFontSizeWithLabel(label: UILabel) -> CGFloat {
if label.adjustsFontSizeToFitWidth == true {
var currentFont: UIFont = label.font
let originalFontSize = currentFont.pointSize
var currentSize: CGSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])
while currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor) {
currentFont = currentFont.fontWithSize(currentFont.pointSize - 1)
currentSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])
}
return currentFont.pointSize
}
else {
return label.font.pointSize
}
}
Objective-C
- (CGFloat)getApproximateAdjustedFontSizeWithLabel:(UILabel *)label {
if (label.adjustsFontSizeToFitWidth) {
UIFont *currentFont = label.font;
CGFloat originalFontSize = currentFont.pointSize;
CGSize currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];
while (currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor)) {
currentFont = [currentFont fontWithSize:currentFont.pointSize - 1];
currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];
}
return currentFont.pointSize;
}
else {
return label.font.pointSize;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…