Nanoc
Nanoc

Reputation: 2381

Problems resizing UILabel inside custom UITableViewCell

I'm trying to create a UITableViewCell with many items inside but I have problems with UILabels.

When using default Styles for UITableViewCell, TextLabel and DetailTextLabel just get properly height to fit content, and I only have to use heightForRowAtIndexPath to calculate row height.

But with my custom cell, UILabels don't resize their height, always keep the size I set on the interface builder, i'm trying this

    CGRect frame;    
    cell.title.text = item.title;
    frame.origin = cell.title.frame.origin;
    frame.size = [item.title sizeWithFont:[UIFont boldSystemFontOfSize:17]
                       constrainedToSize:CGSizeMake(FB_Cell_width, 4000) lineBreakMode:cell.title.lineBreakMode];

    cell.title.frame = frame;

But the UILabel size doesn't change.

I try:

cell.title.text = item.title;
[cell.title sizeToFit];

But size still doesn't change.

How and where I need to change the UILabel frame to fit its content?

EDIT: I just untick the use autolayout option and now it seems to work.

Upvotes: 2

Views: 1428

Answers (2)

user1997077
user1997077

Reputation: 117

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 UILabel *title =  [[UILabel alloc]init]; 
 title.numberOfLines = 0;  
 title.text = item.title;
 float height =  [self heightForText:title.text];
 title.frame = CGRectMake(10, 10, 40, height);
 [cell addSubView:title];
}

- (CGFloat)heightForText:(NSString *)bodyText
{
    UIFont *cellFont = [UIFont systemFontOfSize:30];
    CGSize constraintSize = CGSizeMake(500, MAXFLOAT);
    CGSize labelSize = [bodyText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat height = labelSize.height + 10;
    return height;
}

//try it like this may be it will helps u

Upvotes: 1

Ahmed Z.
Ahmed Z.

Reputation: 2337

Use

cell.title.numberOfLines = 0; //makes your label of unlimited numberoflines
cell.title.text = item.title;
[cell.title sizeToFit];

Upvotes: 0

Related Questions