0
votes

I have a UITableView that displays a UILabel in each cell. The text length varies for each item.

[@"Test1",@"Test 245", @Test 568974"]

Now I want to identify the font size that can correctly fit the largest text. In this case I need to find the font size of UILabel that can correctly display the text @Test 568974" with out any truncation.

I have tried using the

adjustsFontSizeToFitWidth

property and also set

Automatically Adjust Font

in story board with minimum font size. But that makes each text to have a different font size.

How to do it?

3

3 Answers

0
votes

I finally found the solution,

-(CGFloat)findFontSizeforLabel:(UILabel*)label{
    CGFloat minFontSize = 22;
    for(Product *product in products){
        CGFloat fontSize = 22.0;
        while(fontSize > 0){
            NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"fontname" size:fontSize]};
            CGSize size = [product.title sizeWithAttributes:attributes];
            if(size.width < label.frame.size.width - 15){
                if(fontSize < minFontSize){
                    minFontSize = fontSize;
                }
                break;
            }
            fontSize--;
        }
    }
    return minFontSize;
}
0
votes

NSString has a method sizeWithAttributes:

Create a dictionary with the desired text attributes, e.g.:

attrs = [NSDictionary dictionaryWithObject:yourFont forKey: NSFontAttributeName]

and use the method above to get the bounding rectangle. Note that you need to round the returned fractional values to integral values.

With that do a binary search between reasonable font sizes to fit your largest label.

0
votes

To make label resizable add to interface builder constraints like this: enter image description here and set for your table rowHeight to Automatic and estimatedRowheight more than 45:

tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension

This makes your cell adjust label height. If you want to get label height programmatically, use:

NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:14]};
CGRect rect = [textToMeasure boundingRectWithSize:label.frame.size
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:attributes
                                          context:nil];

This gives you size text for given label size and attributes