简体   繁体   中英

Change tableview row height based on multiple cell xib

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 ?

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?

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM