8

我有一张带有静态单元格的表格。对于一个单元格,我想根据标签的高度(在该单元格内)更改其高度,同时保持所有其他单元格的高度不变。如何获取当前单元格的高度?或者也许有更好的方法?

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([indexPath section] == 2) {
        return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height;
    } else {
        return ...; // what should go here, so the cell doesn't change its height?
    }
}
4

6 回答 6

12

您可以致电:

[super tableView:tableView heightForRowAtIndexPath:indexPath] 

在 else 块中,因此您不必担心是否更改了默认高度。

于 2013-04-10T14:14:00.613 回答
4

您可以获取/设置默认高度tableView.rowHeight,或者您可以在更改单元格高度之前存储您的高度,这样您就可以从某个变量中获取默认高度;

于 2013-04-10T13:55:39.977 回答
1

请做这个

if ([indexPath section] == 2)
{
    if(indexPath.row == 1)
         return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height; 
    else 
         tableView.rowHeight
}
于 2013-04-10T13:56:45.013 回答
1

@talnicolas 很好的答案,这里是 Swift 3:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 2 {
        let easy = self.myLabel.frame
        return easy.origin.y *2 + easy.size.height
    } else {
        return super.tableView(tableView, heightForRowAt: indexPath)
    }
}
于 2017-04-28T19:47:35.007 回答
0

您可能想要计算受限宽度中的标签高度。在这种情况下,您可以创建这样的方法:

- (CGFloat)textHeightOfMyLabelText {
    CGFloat textHeight = [self.myLabel.text sizeWithFont:self.myLabel.font constrainedToSize:LABEL_MAX_SIZE lineBreakMode:self.myLabel.lineBreakMode].height;
    return textHeight;
}

并使用结果- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath。不要忘记添加标签的边距值。

于 2013-04-10T13:57:26.140 回答
0
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == youSectionNumber)
    {
        if (indexPath.row == numberOfrow)
        {
            return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height;
        }
    }

      return 44; // it is default height of cell;
}
于 2013-04-10T13:59:22.697 回答