Ios – custom UITableviewcell height not set correctly

iosobjective cuitableview

I explored the existing Q&As on SO about this question but did not find my answer.

I know this is caused by tableview not knowing the height of the custom cell at run time,but not sure how to get over this. This is iOS 8 + Xcode 6. I did all the auto layout required methods for intrinsic size of the custom cell…

  • Standard tableview with standard cells, only one (row = 2) created in code as custom cell;

    customCell:

    -(CGSize)intrinsicContentSize
    

    {
    //hardcode for testing purposes

    return CGSizeMake(500.0, 450.0);
    

    }

  • when running on iOS simulator, found that the customCell is displayed "underneath" other cells below its row, with height standard, the same way other standard cell height is set, instead of its height set much bigger than other cells.

In table view controller:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell;
    pageViewCellTableViewCell* customCell;

    if (indexPath.row != 2)
    {
       cell = [tableView dequeueReusableCellWithIdentifier:@"regularCell" forIndexPath:indexPath];


        cell.textLabel.text = [NSString stringWithFormat:@"Table Row %lu", indexPath.row];
        return cell;
    }
    else
    {
        customCell = [tableView dequeueReusableCellWithIdentifier:@"customCell"] ;

        if (customCell == nil) {

            customCell = [[customCell alloc] init];

        }

        customCell.parentViewController = self;


        [customCell  setNeedsUpdateConstraints];
        [customCell setNeedsLayout];
        [customCell setNeedsDisplay];


        return customCell;

    }

    return nil ;
}

- (CGFloat)tableView: (UITableView*)tableView EstimatedHeightForRowAtIndexPath: (NSIndexPath*) indexPath
 {
     if (indexPath.row != 2)
         return 10;
     else
         return 450;
 }

 - (CGFloat)tableView: (UITableView*)tableView HeightForRowAtIndexPath: (NSIndexPath*) indexPath
 {
     if (indexPath.row != 2)
         return 10;
     else
         return 450;
 }

When running on simulator:

Got the following Error msg:
Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.

screenshot of simulator, see Row 2 got tucked under other rows<code>enter code here</code>

Best Answer

I faced a similar error couple of days ago. I suggest you to check the Auto Layout constraints once more.

When setting the tableView.rowHeight = UITableViewAutomatic you have to make sure that each element in the cell has a leading,top & bottom constraints. Else swift can't change the height dynamically based on content size.

Related Topic