iOS: finding correct font size to fit in a UILabel depending on its size

好久不见. 提交于 2019-12-02 10:33:15
+(void)resizeFontForLabel:(UILabel*)aLabel{

    // use font from provided label so we don't lose color, style, etc
    UIFont *font = aLabel.font;

    float lblWidth = aLabel.frame.size.width;
    float lblHeight = aLabel.frame.size.height;

    CGFloat fontSize = [font pointSize];
    UIFont *newFont = font;
    TRC_DBG(@"%@", aLabel.text);
    CGFloat height = [aLabel.text sizeWithFont:font constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:aLabel.lineBreakMode].height;

    TRC_DBG(@"Label Height %f Constraint height %f", lblHeight, height);
    //Reduce font size while too large, break if no height (empty string)
    while (height > lblHeight && height != 0) {
        fontSize--;
        newFont = [UIFont fontWithName:font.fontName size:fontSize];
        height = [aLabel.text sizeWithFont:newFont constrainedToSize:CGSizeMake(lblWidth,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping].height;
        TRC_DBG(@"Constrained Height %f", height);
    };


    TRC_DBG(@"Font size before adjustment %f", aLabel.font.pointSize);
    // Set the UILabel's font to the newly adjusted font.
    aLabel.font = newFont;
    TRC_DBG(@"Adjust to font size of %f", newFont.pointSize);
    [aLabel setNeedsLayout];
}

In storyboard click on adjust to fit and pick a minimum size.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!