Dynamically increase height of UILabel & TableView Cell?

Dheeraj Kumar picture Dheeraj Kumar · Mar 17, 2016 · Viewed 32.1k times · Source

I have a UITableView in which i am displaying a custom cell.I my cell i have two label & one view as below in picture.

enter image description here

I have given constraint of left view like this

Item label constraints

enter image description here

center view constraints

enter image description here

right view constarints

enter image description here
I am using a bean class to store data for two labels & add that bean object into one array.I am using below code in heightForRowAtIndexPath.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    // Calculate a height based on a cell
    if(!self.customCell) {
        self.customCell = [self.tableView dequeueReusableCellWithIdentifier:@"thirdcell"];
    }

    // Configure the cell
    Instrument *inst=[arr_instSpecs objectAtIndex:indexPath.row];
    self.customCell.label_item.text=inst.item;
    self.customCell.label_desc.text=inst.desc;


    // Layout the cell

    [self.customCell layoutIfNeeded];

    // Get the height for the cell

    CGFloat height = [self.customCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // Padding of 1 point (cell separator)
    CGFloat separatorHeight = 1;

    return height + separatorHeight;
}

Problem is neither height of label is increasing nor of table view cell.I have explained everything. I want to make size of label increase when there is increase in label's text & also when label size increase then height of cell must increase.

Answer

Bharat Modi picture Bharat Modi · Mar 17, 2016

First of all you should not calculate height manually in auto layout environment. Just set both labels TopSpace and BottomSpace to cell's contentView and make sure you set both labels NumberOfLines to 0 and LineBreakMode to WordWrap.

And the other constraint are as below,

ItemLabel:

enter image description here

SeparatorView:

enter image description here

DescriptionLabel:

enter image description here

And add the delegates for height as below,

#pragma mark - UITableView Delegates
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 44.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

You should get the output as below,

enter image description here

Hope this would help you.