Why does this break UILabel adjustsFontSizeToFitWidth?
ios, objective-c
Solution
Well, it appears that this is basically a bug, perhaps fixed in Xcode 6. This works in iOS 7 - I have not tested it in any other version.
In the meantime, this is the method I'm using to scale down text to fit in my UILabel, with multiple lines and AttributedString:
-(void)whAlertDisplayTheNotice:(UILabel*)inputlabel theNotice:(NSString*)theNotice {
float maxFontSize=80.0;
NSRange tmpRange=NSMakeRange(0,theNotice.length);
NSMutableParagraphStyle *paragraph=[[NSMutableParagraphStyle alloc]init];
paragraph.lineBreakMode=NSLineBreakByWordWrapping;
paragraph.alignment=NSTextAlignmentCenter;
paragraph.maximumLineHeight=maxFontSize;
paragraph.lineSpacing=0;
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:theNotice];
[attString addAttribute:NSParagraphStyleAttributeName
value:paragraph
range:tmpRange];
[attString addAttribute:NSForegroundColorAttributeName
value:[UIColor blackColor]
range:tmpRange];
CGSize constraintSize=CGSizeMake(inputlabel.frame.size.width, CGFLOAT_MAX);
CGRect labelSize;
for(short i=maxFontSize; i>8; i--){
[attString addAttribute:NSFontAttributeName
value:[UIFont fontWithName:@"MV Boli" size:i]
range:tmpRange];
inputlabel.attributedText=attString;
labelSize=[inputlabel.attributedText boundingRectWithSize:constraintSize
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
context:nil];
if(labelSize.size.height<inputlabel.frame.size.height){
NSLog(@"fontsize is:%li",(long)i);
break;
}
}
}
Problem
iOS 7, Xcode 5 Using a UILabel, this code works (autosizes the text to fit): ``` self.testLabel.numberOfLines=0; self.testLabel.lineBreakMode=NSLineBreakByWordWrapping; self.testLabel.adjustsFontSizeToFitWidth=YES; self.testLabel.minimumScaleFactor=0.1; self.testLabel.textAlignment=NSTextAlignmentCenter; [self.testLabel.font fontWithSize:100.0]; ``` But adding the "setFont" line causes it to not scale the font to fit: ``` [self.testLabel setFont:[UIFont fontWithName:@"Helvetica Neue" size:62.0f]]; //THIS LINE CAUSES THE FONT SCALING TO FAIL self.testLabel.numberOfLines=0; self.testLabel.lineBreakMode=NSLineBreakByWordWrapping; self.testLabel.adjustsFontSizeToFitWidth=YES; self.testLabel.minimumScaleFactor=0.1; self.testLabel.textAlignment=NSTextAlignmentCenter; [self.testLabel.font fontWithSize:100.0]; ``` Does anyone know a fix for this problem?