简体   繁体   中英

Change font size in UILabel depending on string length

Let's say I have a UILabel which covers the entire window of the app. In this label is displayed random text with different lengths. Is it possible to change the text font size dependant on the text length?

Yes, UILabel can do that for you, just do:

theLabel.adjustsFontSizeToFitWidth = YES;
theLabel.minimumFontSize = MIN_FONT_SIZE;

Attention to this (from the documentation):

This property is effective only when the numberOfLines property is set to 1.

I created a category method at one point. You basically feed it a rectangle and it will return a font that fits. Maybe you can glean something from the following crude example:

- (UIFont *)fontSizeForRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(UILineBreakMode)lineBreakMode minFontSize:(CGFloat)minFontSize 
    {

            CGFloat fontSize = [font pointSize];
            UIFont *tempFont = [UIFont fontWithName:[font fontName] size:[font pointSize]];
            CGFloat acceptableFontSize = fontSize;
            while (fontSize > minFontSize) 
            {
               UIFont *testFont = [UIFont fontWithName:[tempFont fontName] size:fontSize];
               CGSize sizeWithTestFont = [self sizeWithFont:testFont constrainedToSize:CGSizeMake(rect.size.width, 99999.0) lineBreakMode:lineBreakMode];
                if (sizeWithTestFont.height > rect.size.height)
                    fontSize -= 1.0f; //Shrink the font size by a point
                else 
                {
                    //Fits.  Use it.  
                    acceptableFontSize = fontSize;
                    break;
                }
            }

            return [UIFont fontWithName:[font fontName] size:acceptableFontSize];
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM