简体   繁体   English

根据字符串长度更改UILabel中的字体大小

[英]Change font size in UILabel depending on string length

Let's say I have a UILabel which covers the entire window of the app. 假设我有一个UILabel ,它覆盖了应用程序的整个窗口。 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: 是的,UILabel可以为您做到这一点,只需执行以下操作:

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. 仅当numberOfLines属性设置为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];
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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