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

后端 未结 2 1781
攒了一身酷
攒了一身酷 2021-01-27 08:27

I have a UILabel whose property text I would like to set paragraphs of text to using NSString.

I have an array in which I store a

相关标签:
2条回答
  • 2021-01-27 08:56

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

    0 讨论(0)
  • 2021-01-27 09:10
    +(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];
    }
    
    0 讨论(0)
提交回复
热议问题