为自定义单元格设置uitableviewcell高度

时间:2012-05-16 21:38:55

标签: objective-c ios cocoa-touch uitableview

我希望根据您在Interface Builder中设置自定义单元格的值动态设置单元格高度。这没有用,所以我继续前进并在Apples文档中找到了可用于设置单元格高度的方法 - tableView:heightForRowAtIndexPath:

但是我不确定我是否正确使用它,因为我的tableviewcells没有调整它们的高度它们都保持相同的标准尺寸。这是我在这里使用的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Set cell height
    [self tableView:tableView heightForRowAtIndexPath:indexPath];

    // Configure the cell using custom cell
    [[NSBundle mainBundle] loadNibNamed:@"CustomcellA" owner:self options:nil];
    cell = customcellA; // customcellA getters and setters are set up in .h

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:7)

假设第三个单元格的高度是两倍:

- (CGFloat)   tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 2)
        return 88;
    return 44;
}

tableView将调用此方法。

你不应该这样做:

[self tableView:tableView heightForRowAtIndexPath:indexPath];

您应该如何确保正确的单元格的indexPath被识别为其他尺寸。

一般规则:
如果实现委托协议的方法,则永远不会自己调用它。只有具有符合协议的委托的类的对象才会调用委托方法。

答案 1 :(得分:0)

将自动调用heightForRowAtIndexPath,您需要返回所需的自定义高度。因此,您需要根据数据或基于高度的任何内容返回动态高度,而不是返回44.

相关问题