根据多个单元格xib更改tableview行高 [英] Change tableview row height based on multiple cell xib

查看:24
本文介绍了根据多个单元格xib更改tableview行高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格视图,其中单元格是从 xib 文件中填充的.有 2 个单元格 xib 文件在 tableview 中动态显示不同的内容.

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.

我想根据正在填充的单元格设置 tableview 的行高.我使用 heightForRowAtIndexPath 根据单元格 xib 设置行的高度.代码如下:

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;
}

这样做在 tableview 中不显示任何内容,只显示空单元格.如果没有 heightForRowAtIndexPath,单元格将填充正确的内容,但使用默认的 tableview 行高.

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.

如何在 tableview 中设置 row height,其 cells 是从 xib 文件 填充的?

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

推荐答案

你应该首先在 viewDidLoad 方法中的某个地方实例化你的 2 个单元格:

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;

}

这篇关于根据多个单元格xib更改tableview行高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆