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

时间:2009-06-01 03:42:15

标签: ios iphone

我希望我的单元格高度根据其中显示的文本而改变。文本会有所不同,我基本上希望细胞改变大小。以下是我到目前为止的情况:

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

2 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:3)

如果所有行都具有相同的高度,我认为在你的情况下是正确的,你可以在tableview控制器中设置setRowHeight。

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization.
        NSLog(@"%s", __FUNCTION__);
        [self.tableView setRowHeight:110];
    }
    return self;
}

行宽可以通过表格的超视宽度

来控制
相关问题