How can I make text in a UILabel shrink font size

后端 未结 4 627
慢半拍i
慢半拍i 2021-02-03 22:45

If a UILabel contains too much text, how can I setup my label so that it shrinks font-sizes?

Here is how I am setting up my UILabel:

     descriptionLabe         


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-03 23:12

    To resize the text in a multi-line UILabel, you can use this helper method (based on code from 11 Pixel Studios):

    + (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize { 
     // use font from provided label so we don't lose color, style, etc
     UIFont *font = aLabel.font;
    
     // start with maxSize and keep reducing until it doesn't clip
     for(int i = maxSize; i >= minSize; i--) {
      font = [font fontWithSize:i];
      CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);
    
      // This step checks how tall the label would be with the desired font.
      CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
      if(labelSize.height <= aLabel.frame.size.height)
       break;
     }
     // Set the UILabel's font to the newly adjusted font.
     aLabel.font = font;
    }
    

提交回复
热议问题