tags:

views:

164

answers:

2

Yeah, there's this cool myLabel.adjustsFontSizeToFitWidth = YES; property. But as soon as the label has two lines or more, it won't resize the text to anything. So it just gets truncated with ... if it doesn't fit into the rect.

Is there another way to do it?

+1  A: 

Also set myLabel.numberOfLines = 10 or to whatever the max number of lines you want.

Pyro2927
+1  A: 

If you want to make sure the label fits in the rectangle both width and height wise you can try different font size on the label to see if one will fit.

This snippet starts at 300 pt and tries to fit the label in the targeted rectangle by reducing the font size.

- (void) sizeLabel: (UILabel *) label toRect: (CGRect) labelRect  {

    // Set the frame of the label to the targeted rectangle
    label.frame = labelRect;

    // Try all font sizes from largest to smallest font size
    int fontSize = 300;
    int minFontSize = 5;

    // Fit label width wize
    CGSize constraintSize = CGSizeMake(label.frame.size.width, MAXFLOAT);

    do {
            // Set current font size
            label.font = [UIFont boldSystemFontOfSize:fontSize];

            // Find label size for current font size
            CGSize labelSize = [[label text] sizeWithFont:label.font
                    constrainedToSize:constraintSize
                    lineBreakMode:UILineBreakModeWordWrap];

            // Done, if created label is within target size
            if( labelSize.height <= label.frame.size.height )
                    break;

            // Decrease the font size and try again
            fontSize -= 2;

    } while (fontSize > minFontSize);
}
Niels Castle