0
votes

I have a tableview where cells are populated from the xib files. There are 2 cell xib files displaying different content in the tableview dynamically.

I want to set the row height for the tableview based on which cell is being populated. I used heightForRowAtIndexPath to set the height of the row depending on the cell xib. Following is the code:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentBoxCell *commentBoxCell;
    UserCommentCell *userCommentCell;

    if ([commentsAndTagsArray count]) {

        if (!commentBoxCell){

            return commentBoxCell.bounds.size.height;
        }

        if (!userCommentCell){

            return userCommentCell.bounds.size.height;
        }
    }
    //default height of the cell
    return 44;
}

Doing this displays nothing in the tableview, just empty cells. Without the heightForRowAtIndexPath, the cells are populated with correct content but with default tableview row height.

How can I set the row height in tableview whose cells are populated from the xib files?

2
How you are checking commentBoxCell and userCommentCell in if? By looking to your code it will be always false as it is not initialised. - Iftikhar Ali Ansari
This method always return 44 because commentBoxCell and userCommentCell are both nil. You need to use [tableView dequeuReuseableCellWithIdentifier:atIndexPath:]. - kientux
I have used [tableView dequeuReuseableCellWithIdentifier:atIndexPath:] in cellForRowAtIndexPath - s.d.

2 Answers

0
votes

it looks like commentsAndTagsArray does is not nill and have 1 or more objects so it enter the first if, after that it does nothing as your cell's aren't initialized and there's not default return there.

Now heightForRowAtIndexPath: comes before cellForRowAtIndexPath: so you don't have a cell yet at this point, but you should be able to know what kind of cell do you want to present using the indexPath or whatever logic you're using to identify which cell type to create, why don't you use that logic to select the height instead?

0
votes

You should first instantiate your 2 cells like this somewhere in your viewDidLoad method:

commonetBoxCell = [[[NSBundle mainBundle] loadNibNamed:@"CommentBoxCellNib" owner:self options:nil] firstObject];
userCommentCell = [[[NSBundle mainBundle] loadNibNamed:@"UserCommentCellNib" owner:self options:nil] firstObject];

Then, you should update the height method like this:

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

{

CGFloat height = 44.0;
if (<this is a comment box cell>) {
    [commonetBoxCell updateWithData];
    height = [commonetBoxCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}
if (<this is a user comment cell>) {
    [userCommentCell updateWithData];
    height = [userCommentCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
}

return height;

}