Mitch1972
Mitch1972

Reputation: 69

Shrink text inside UIlabel programmatically

I am trying to shrink a text inside a UILabel. My text is a string, I've got a max of 7 lines and sometimes are not enough then I need shrink the text to fit inside that 7 lines. Here my code.`

// create label
    UILabel *desc = [[UILabel alloc] initWithFrame:CGRectMake(5, 220, 310, 200)];
    desc.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
    desc.font = [UIFont fontWithName:@"Helvetica" size:30];
    desc.numberOfLines = 7;
    desc.textColor = [UIColor blackColor];
    desc.layer.borderColor = [UIColor blackColor].CGColor;
    desc.layer.borderWidth = 1.0;
    desc.text = // MY string ;
    desc.adjustsFontSizeToFitWidth = YES;
    [self.view addSubview:desc];`

I tried even [desc sizeToFit];

I cannot figure out what I am doing wrong. I have already checked all the posts about this.

Thanks for any help

Upvotes: 0

Views: 691

Answers (2)

Bejmax
Bejmax

Reputation: 945

You can use a helper function to resize it. Here is an example. I simply changed lineBreakMode to NSLineBreakByWordWrapping (since previous was deprecated in iOS6).

+ (void)resizeFontForLabel:(UILabel*)aLabel maxSize:(int)maxSize minSize:(int)minSize
{
    // use font from provided label so we don't lose color, style, etc
    UIFont *font = aLabel.font;

    // start with maxSize and keep reducing until it doesn't clip
    for(int i = maxSize; i > 10; i--) {
        font = [font fontWithSize:i];
        CGSize constraintSize = CGSizeMake(aLabel.frame.size.width, MAXFLOAT);

        // This step checks how tall the label would be with the desired font.
        CGSize labelSize = [aLabel.text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
        if(labelSize.height <= aLabel.frame.size.height)
            break;
    }
    // Set the UILabel's font to the newly adjusted font.
    aLabel.font = font;
}

Upvotes: 1

AlexWien
AlexWien

Reputation: 28737

As far as I know UILabel does not support automatic calculation of font size in multi line mode. You could iterating the font sizes untill it fits.

Also look at

sizeWithFont:forWidth:lineBreakMode:

Upvotes: 0

Related Questions