【问题标题】:Within cellForRowAtIndexPath getting height of cell when cells are variable height当单元格是可变高度时,在 cellForRowAtIndexPath 中获取单元格的高度
【发布时间】:2012-08-21 21:19:12
【问题描述】:

我在我的表格视图中创建了自定义单元格,有些单元格有图像并且很高,有些只是文本。单元格的高度是在 heightForRowAtIndexPath 中计算的,我相信这是在调用 cellForRowAtIndexPath 之前完成的。无论高度如何,我都想在单元格底部放置一个图像视图,但我不确定如何从 cellForRowAtIndexPath 中获取计算出的高度?

【问题讨论】:

  • CGFloat height = [tableView.delegate tableView:tableView heightForRowAtIndexPath:indexPath];

标签: iphone ios


【解决方案1】:

回答太晚了..

但是,就像@user216661 指出的那样,获取 Cell 或 ContentView 的高度的问题在于它返回了单元格的原始高度。 Incase 具有可变高度的行,这是一个问题。

更好的解决方案是获取单元格的矩形 (rectForRowAtIndexPath),然后从中获取高度。

- (UITableViewCell *)tableView:(UITableView *)iTableView cellForRowAtIndexPath:(NSIndexPath *)iIndexPath {
    UITableViewCell *aCell = (UITableViewCell *)[iTableView dequeueReusableCellWithIdentifier:aCellIdentifier];
    if (aCell == nil) {
        CGFloat aHeight = [iTableView rectForRowAtIndexPath:iIndexPath].size.height;
        // Use Height as per your requirement.
    }

    return aCell;
}

【讨论】:

    【解决方案2】:

    您可以询问代表,但您将询问两次,因为 tableView 已经询问并相应地调整单元格的大小。最好从细胞本身找出来……

    // in cellForRowAtIndexPath:, deque or create UITableViewCell *cell
    // this makes the call to heightForRow... and sizes the cell
    CGFloat cellHeight = cell.contentView.bounds.size.height;
    
    // alter the imageView y position (assuming the rest of the frame is correct)
    CGRect imageFrame = myImageView.frame;
    imageFrame.y = cellHeight - imageFrame.size.height;   // place the bottom edge against the cell bottom
    myImageView.frame = imageFrame;
    

    【讨论】:

    • 这个好像不行,cell.contentView.bounds.size.height返回的高度和heightForRowAtIndexPath中计算的高度不同
    • 马克,你找到解决方案了吗? cell.contentView 似乎正在返回单元格的原始高度和宽度。
    【解决方案3】:

    您可以自己调用 heightForRowAtIndexPath!只需将 cellForRowAtIndexPath 中的 indexPath 作为参数传递,您就可以知道您正在设置的单元格的高度。

    假设您使用的是 UITableViewController,只需在 cellForRowAtIndexPath 中使用它...

    float height = [self heightForRowAtIndexPath:indexPath]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多