In case you are still searching for a better solution, I think this is what you want:
A Boolean value indicating whether the font size should be reduced in order to fit the title string into the label’s bounding rectangle (this property is effective only when the numberOfLines
property is set to 1).
When setting this property, minimumScaleFactor
MUST be set too (a good default is 0.5).
var adjustsFontSizeToFitWidth: Bool { get set }
@property(nonatomic) BOOL adjustsFontSizeToFitWidth;
A Boolean value indicating whether spacing between letters should be adjusted to fit the string within the label’s bounds rectangle.
var allowsDefaultTighteningForTruncation: Bool { get set }
@property(nonatomic) BOOL allowsDefaultTighteningForTruncation;
Source.
This is how I get UILabel Autoshrink
work (especially for height of label font fitting in 4s device from 6s Plus Storyboard) in iOS 9.2, Xcode 7.2 ...
minimumFontSize
is deprecated in iOS 6.
So use minimumScaleFactor
instead of minmimumFontSize
.
lbl.adjustsFontSizeToFitWidth = YES
lbl.minimumScaleFactor = 0.5
Swift 5
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
also my solution is the boolean label.adjustsFontSizeToFitWidth = YES; BUT. You must in the interface Builder the Word Wrapping switch to "CLIP". Then autoshrink the Labels. This is very important.
In Swift 3 (Programmatically) I had to do this:
let lbl = UILabel()
lbl.numberOfLines = 0
lbl.lineBreakMode = .byClipping
lbl.adjustsFontSizeToFitWidth = true
lbl.minimumScaleFactor = 0.5
lbl.font = UIFont.systemFont(ofSize: 15)
You can write like
UILabel *reviews = [[UILabel alloc]initWithFrame:CGRectMake(14, 13,270,30)];//Set frame
reviews.numberOfLines=0;
reviews.textAlignment = UITextAlignmentLeft;
reviews.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:12];
reviews.textColor=[UIColor colorWithRed:0.0/255.0 green:0.0/255.0 blue:0.0/255.0 alpha:0.8];
reviews.backgroundColor=[UIColor clearColor];
You can calculate number of lines like that
CGSize maxlblSize = CGSizeMake(270,9999);
CGSize totalSize = [reviews.text sizeWithFont:reviews.font
constrainedToSize:maxlblSize lineBreakMode:reviews.lineBreakMode];
CGRect newFrame =reviews.frame;
newFrame.size.height = totalSize.height;
reviews.frame = newFrame;
CGFloat reviewlblheight = totalSize.height;
int lines=reviewlblheight/12;//12 is the font size of label
UILabel *lbl=[[UILabel alloc]init];
lbl.frame=CGRectMake(140,220 , 100, 25);//set frame as your requirement
lbl.font=[UIFont fontWithName:@"Arial" size:20];
[lbl setAutoresizingMask:UIViewContentModeScaleAspectFill];
[lbl setLineBreakMode:UILineBreakModeClip];
lbl.adjustsFontSizeToFitWidth=YES;//This is main for shrinking font
lbl.text=@"HelloHelloHello";
Hope this will help you :-) waiting for your reply
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With