UILabel is not auto-shrinking text to fit label size

后端 未结 17 637
感动是毒
感动是毒 2020-12-04 06:53

I have this strange issue, and im dealing with it for more than 8 hours now.. Depending on situation i have to calculate UILabels size dynamically,
e.g

17条回答
  •  悲&欢浪女
    2020-12-04 07:27

    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

提交回复
热议问题