根据多个单元格xib更改tableview行高

时间:2015-10-26 15:10:52

标签: ios objective-c uitableview

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

我想根据正在填充的单元格设置tableview的行高。我使用heightForRowAtIndexPath来设置行的高度,具体取决于单元格xib。以下是代码:

- (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行高。

如何设置row height tableview cells填充xib files

2 个答案:

答案 0 :(得分:0)

它看起来像commentsAndTagsArray不是nill并且有一个或多个对象所以它输入第一个if,之后它什么也没做,因为你的单元格没有被初始化而且没有默认值回到那里。

现在heightForRowAtIndexPath:在cellForRowAtIndexPath之前出现:所以你现在还没有一个单元格,但是你应该能够知道你想要使用indexPath呈现什么样的单元格,或者你有什么逻辑。 ;重新使用来识别要创建的单元格类型,为什么不使用该逻辑来选择高度呢?

答案 1 :(得分:0)

您应首先在viewDidLoad方法中的某处实例化这样的2个单元格:

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

然后,您应该像这样更新高度方法:

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

}

相关问题