在表格视图中更改单元格高度目标C.

The*_*ler 4 iphone ios

我根据显示在其中的文本来改变单元格的高度.文本会有所不同,我基本上希望细胞改变大小.这是我到目前为止:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DefaultCell1"];
    CGRect cellRectangle;
    if (cell == nil) {

    cellRectangle = CGRectMake(0.0, 0.0, 300, 110);
    cell = [[[UITableViewCell alloc] initWithFrame:cellRectangle reuseIdentifier:@"DefaultCell1"] autorelease];
    }

    UILabel *label;
    cellRectangle = CGRectMake(10, (40 - 20) / 2.0, 280, 110);

    //Initialize the label with the rectangle.
    label = [[UILabel alloc] initWithFrame:cellRectangle];
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 20;

    label.font = [UIFont fontWithName:@"Helvetica" size:11.0];
    label.text = [[self.person.statusMessages objectAtIndex:indexPath.row]   valueForKey:@"text"];
    CGFloat height = [label.text sizeWithFont:label.font].height;

    //So right here is where I think I need to do something with height and 
    //see it to something tied to he cell

    [cell.contentView addSubview:label];

    [label release];

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*lar 8

您不应该在cellForRowAtIndexPath方法中设置高度.还有另一个名为tableView的UITableViewDatasource方法:heightForRowAtIndexPath:你应该实现它来返回单元格的高度.但要小心使用它; 你不能在这个方法中获得该索引路径的单元格; 如果你这样做,你将构建一个无限的递归循环.

编辑:要清楚; 你需要根据它的内容计算细胞的高度,而不是单元本身.

此外,在创建单元格的代码中,您只需将CGRectZero传递给frame参数即可; 如果你这样做,表视图将计算单元格的框架本身(如果我没记错的话,在OS 3.0中也明确传入框架).