4

我在 TableView 中使用自定义单元格。

单元格高度是根据加载到单元格的 UILabel 中的 NSString 计算的。使用此函数计算大小

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = [self getTableViewRow:tableView index:indexPath];

CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);

CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

CGFloat height = MAX(size.height, 44.0f);

return height + (CELL_CONTENT_MARGIN * 2) + 60;

}

大小计算正确,但是当单元格加载到 uiTableView 时,行具有正确的高度,但单元格没有。

这是我创建我的单元格的地方

//Com Custom Cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"CustomCellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) 
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCellApresentacao" owner:self options:nil];

    if ([nib count] > 0 )
        cell = self.tvCell;    
    else
        NSLog(@"Falhou a carregar o xib");
}    

NSInteger row = [indexPath row];

if(self.myTableView1 == tableView)
    labelDescricaoApresentacao.text = [listData1 objectAtIndex:row];
else if (self.myTableView2 == tableView) 
    labelDescricaoApresentacao.text = [listData2 objectAtIndex:row];
else
    labelDescricaoApresentacao.text = [listData3 objectAtIndex:row];  

return cell;
}

我尝试使用这种方法更改单元格高度

cell.frame.size.height

但它仍然没有加载正确的高度。

我必须在 customCell 的 xib 中做任何事情吗?我应该如何将单元格高度更新为与行相同的大小?

4

4 回答 4

4

你在哪里设置 cell.frame.size.height?我建议尝试把它放在这里:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.frame = CGRectMake(0,0,320.0f,30.0f);
}

此方法在单元格显示之前被调用,是对单元格进行任何视觉更改的好地方。

于 2012-02-10T17:09:42.370 回答
2

如果您从 NIB(或故事板)加载原型单元格,它们将具有与 UITableView 中定义的高度相同的高度。

picciano 的解决方案在我的应用程序中不起作用。

我改用了这个委托函数,它可以工作:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexpath{
        CGFloat *theCellHeight=xxx;
        //determine here which section/row it is, and the desired height for it, put it in "theCellHeight"
        return theCellHeight;
}

希望对你有帮助

备注:尽管如此,似乎没有办法获取单元格的内容/引用,因为在该函数内部调用 cellAtIndexPath 时会冻结应用程序。所以你必须以编程方式在一个数组中构建你的表,然后创建它,这样它就降低了 NIB 的用处。

于 2012-04-18T21:31:22.213 回答
0

即使您正确设置了行的高度heightForRowAtIndexPath,单元格的内容也将始终具有固定的高度,因为您正在从笔尖加载单元格。要使单元格内容动态更改高度,您需要cellForRowAtIndexPath使用您在heightForRowAtIndexPath:

于 2012-02-10T17:21:45.693 回答
0

我的猜测是您没有正确处理单元格的大小调整。

我不确定何时设置单元格的框架,但我猜它是在您从 tableView:cellForRowAtIndexPath: 方法返回一个单元格之后设置的,这意味着该单元格被创建或重用,然后它的框架被设置。

你应该做的是覆盖单元格的 setFrame: 方法,并在调用 super 之后修改它的子视图框架以适应新的大小。

您还可以在 Interface Builder 上的子视图上使用自动调整大小的掩码,以便它们自动适应新框架。

于 2012-02-10T17:22:40.183 回答