4

我为每个 UITableViewCell 设置了高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

我需要获取每个 UITableViewCell 的高度

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

因为我需要在不同的单元格中添加SubView。

我尝试使用cell.frame& cell.bounds& cell.contentView.frame,但高度没有改变。

4

5 回答 5

8

这可能为时已晚,但您可以使用委托方法:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect cellSize = cell.frame;
}

希望它可以帮助任何人,如果我错过了什么,请告诉我。:)

于 2013-09-01T09:23:27.207 回答
2

UITableViews方法呢, - (CGRect)rectForRowAtIndexPath:(NSIndexPath *)indexPath

得到这样的矩形,

CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
于 2015-03-11T08:24:25.963 回答
2

我这样解决了:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // create object
    id myObj = [_arrayEvents objectAtIndex:indexPath.row];

    // create static identifier
    static NSString * myIdentifier = @"Cell";

    // create static UITableViewCell
    static UITableViewCell * cell;

    // create cell with object
    cell = [self buildCell:myIdentifier tableView:tableView obj: myObj];

    return cell.contentView.frame.size.height;

}
于 2013-11-29T18:23:28.050 回答
1

它们是不同的东西。在 heightForRowAtIndexPath: 你告诉 UITableView 它应该使用多少垂直空间来显示相应的单元格,但这不会影响单元格的实际大小!因此,如果您希望它们匹配,您必须手动设置尺寸。

如果您不想/需要调整单元格框架的大小,您应该简单地将高度存储在自定义单元格类的属性中。

于 2012-12-20T08:59:51.297 回答
-1

正如@ilMalvagioDottorProsci 所说,heightForRowAtIndexPath 函数返回的值不会影响单元格的实际大小。

如果你想实现每行高度由单元格高度决定。我有一个技巧。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id aKey = [self buildCellCacheKey:indexPath];
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];

    if ([_cellCache objectForKey:aKey]==nil) {
        [_cellCache setObject:cell forKey:aKey];
    }

    return cell.bounds.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // for flexible height of table view cell.in this way,the cell height won't be caculate twice.
    id aKey = [self buildCellCacheKey:indexPath];
    UITableViewCell *cacheCell = [_cellCache objectForKey:aKey];
    if (cacheCell) {
        [cacheCell retain];
        [_cellCache removeObjectForKey:aKey];
        LOGDebug(@"return cache cell [%d]",indexPath.row);
        return [cacheCell autorelease];
    }

// here is the code you can config your cell..  
}
于 2012-12-20T09:12:11.273 回答