2013-04-10 93 views
8

我有一個靜態單元格的表格。對於一個細胞,我想根據標籤的高度(在細胞內)改變其高度,同時保持所有其他細胞高度不變。我如何獲得當前細胞的高度?或者,也許有更好的方法?heightForRowAtIndexPath中的當前單元格高度?

- (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? 
    } 
} 
+3

您單元的默認高度去那裏。 44如果你沒有改變任何東西。 – Desdenova 2013-04-10 13:50:58

+0

您還可以使用UIKIt對NSString方法'sizeWithFont:'的擴展來計算標籤的單元實際所需高度。 – 2013-04-10 13:56:23

回答

12

您可以撥打:

[super tableView:tableView heightForRowAtIndexPath:indexPath] 

在else塊,所以你不必擔心,如果你永遠改變了默認的高度。

4

可以獲取/設置默認的高度tableView.rowHeight,或者您也可以更改單元格高度前,你的身高存儲,這樣你就可以得到一些變量默認高度;

1

請做一個

if ([indexPath section] == 2) 
{ 
    if(indexPath.row == 1) 
     return self.myLabel.frame.origin.y *2 + self.myLabel.frame.size.height; 
    else 
     tableView.rowHeight 
} 
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使用的結果。 不要忘記添加標籤的保證金值。

+0

是的,thx,我只是要改變它=) – Ossir 2013-04-10 13:59:53

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

@talnicolas偉大的答案,以下是雨燕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) 
    } 
} 
相關問題