Question

I have a custom UITableViewCell that has two UILabels and one UIImageView. I set each UILabel's text based on data objects from a web service. So, until runtime there is no way of knowing the size of the text as it could be anything from my web service call.

Is there a way to tell UILabel to adjust its size automatically, according to its text size or content?

UPDATE

Okay for some reason all the suggested methods make no changes to my UILabel's at all in UITableViewCell.

I am setting the text in the code below:

Example using SujithPt's method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BBCategoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CategoryCell"];
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CategoryCell" owner:self options:nil];
    cell = [topLevelObjects objectAtIndex:0];

    BBFilterCategoryObject *category = self.categories[indexPath.row];

    cell.title.text = category.category.name;
        CGSize labelSize = [self getSizeForText:cell.title.text maxWidth:150 font:@"ChaparralPro-Bold" fontSize:15];

    [cell.title sizeThatFits:labelSize];

    return cell;
}


- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {

    /*! Returns the size of the label to display the text provided
     @param text
     The string to be displayed
     @param width
     The width required for displaying the string
     @param fontName
     The font name for the label
     @param fontSize
     The font size for the label
     */

    CGSize constraintSize;
    constraintSize.height = MAXFLOAT;
    constraintSize.width = width;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
                                          nil];

    CGRect frame = [text boundingRectWithSize:constraintSize
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributesDictionary
                                      context:nil];

                        CGSize stringSize = frame.size;

    return stringSize;

}
Was it helpful?

Solution

Use this method:

/*! Returns the size of the label to display the text provided
    @param text
        The string to be displayed
    @param width
        The width required for displaying the string
    @param fontName
        The font name for the label
    @param fontSize
        The font size for the label
 */
- (CGSize)getSizeForText:(NSString *)text maxWidth:(CGFloat)width font:(NSString *)fontName fontSize:(float)fontSize {
    CGSize constraintSize;
    constraintSize.height = MAXFLOAT;
    constraintSize.width = width;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:fontName size:fontSize], NSFontAttributeName,
                                          nil];

    CGRect frame = [text boundingRectWithSize:constraintSize
                                      options:NSStringDrawingUsesLineFragmentOrigin
                                   attributes:attributesDictionary
                                      context:nil];

    CGSize stringSize = frame.size;
    return stringSize;
}

Edit

Set the label frame using the size returned from the above method.

[cell.title setFrame:CGRectMake(cell.title.frame.origin.x, cell.title.frame.origin.y, sizeFromTheMethod.height, sizeFromTheMethod.width)];

OTHER TIPS

//use this for custom font
CGFloat width =  [label.text sizeWithAttributes:@{NSFontAttributeName:
[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]}].width;

//use this for system font 
CGFloat width =  [label.text sizeWithAttributes:@{NSFontAttributeName
:[UIFont systemFontOfSize:40 ]}].width;

label.frame = CGRectMake(point.x, point.y, width,height);

//point.x, point.y -> origin for label;
//height -> your label height; 

Got it from here

I was facing same issue once. What I did was... created a class which represent UITableViewCell as well as cell configuration properties (height,width..etc)

class Cell{

 NSString * urlLabelString; //which will come from web service


 //it will return height of Cell which can be used in `-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath` delegate method
    -(float)height{

        //calculate size of label using [sizeWithFont][1]  method and add your image height here
        // and return total dynamic cell height
       return totalheight;
     }

}

you can keep array of these class objects as datasource for your UItableView

Hope it helps !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top