Search code examples
iosios7ios8

How can I set same font-scale for multiple labels depending on which one is autoshrinked?


I have 4 label views of which one is supposed to show large numerical values and is set for autoshrink.

My requirement would be to set the same font-scaling or size this label has, after its been auto-adjusted to fit its content, to the other labels too so that the text content looks uniform throughout.

Setting the minimum scale factor didn't help for the other labels because they have content within the frame limits.


Solution

  • There's no way to do this directly, since querying the font of the label where the text has been shrunk to fit, still shows the original font size. You have to do it by iterating over smaller and smaller font sizes until you find the size that fits in your label, and then use that font size to adjust your other labels. In my example below, labelLong is the one whose text can shrink, and labelShort is the one whose text doesn't need to shrink.

    -(void)updateFont {
        NSStringDrawingContext *ctx = [NSStringDrawingContext new];
        ctx.minimumScaleFactor = 1.0;
        UIFont *startingFont = self.labelLong.font;
        NSString *fontName = startingFont.fontName;
        CGFloat startingSize = startingFont.pointSize;
        for (float i=startingSize*10; i>1; i--) { // multiply by 10 so we can adjust font by tenths of a point with each iteration
            UIFont *font = [UIFont fontWithName:fontName size:i/10];
            CGRect textRect = [self.labelLong.text boundingRectWithSize:self.labelLong.frame.size options:NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName:font} context:ctx];
            if (textRect.size.width <= [self.labelLong textRectForBounds:self.labelLong.bounds limitedToNumberOfLines:1].size.width) {
                NSLog(@"Font size is: %f", i/10);
                self.labelShort.font = [UIFont fontWithName:fontName size:i/10];
                break;
            }
        }
    }