2011-07-14 35 views
2

我有一個分組的UITableView。如何根據標籤的高度動態調整UITableViewCell的大小?

我重寫錶行高度,但我想第一行有一個動態高度是基於我的單元格中標籤高度的大小。我怎麼能得到這個高度?

{ 
    CGFloat rowHeight = 0; 

    if(indexPath.section == kBioSection) { 
     switch(indexPath.row) { 
      case kBioSectionDescriptionRow:     
       rowHeight = 100; 
       break; 
      case kBioSectionLocationRow:      
       rowHeight = 44; 
       break; 
      case kBioSectionWebsiteRow:     
       rowHeight = 44; 
       break; 
     } 
    } 
    else { 
     rowHeight = 44; 
    } 

    return rowHeight; 
} 
+1

工作的呢?如果沒有,出了什麼問題? – PengOne

+0

另外,我相信你可以用一個'if'語句完成上面的代碼。 – PengOne

回答

2

的NSString有一個名爲

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode; 

宣佈UIStringDrawing.h

方法它會給你畫這個字符串所需的大小。

您可以獲取所需大小的高度,然後添加任何您想要的內容,如其他標籤/視圖以及它們之間的空間,以計算最終高度。

事情是這樣的:

{ 
    CGFloat rowHeight = 0; 

    if(indexPath.section == kBioSection) { 
     switch(indexPath.row) { 
      case kBioSectionDescriptionRow:     
       CGSize labelSize = [descriptionText sizeWithFont:labelFont forWidth:tableView.frame.size.width - 20 lineBreakMode:UILineBreakModeWordWrap]; //Assuming 10 px on each side of the label 
       rowHeight = labelSize + 50; //Assuming there are 50 px of extra space on the label, besides the text 
       break; 
      case kBioSectionLocationRow:      
       rowHeight = 44; 
       break; 
      case kBioSectionWebsiteRow:     
       rowHeight = 44; 
       break; 
     } 
    } 
    else { 
     rowHeight = 44; 
    } 

    return rowHeight; 
} 
+0

我的tableview似乎崩潰了。我抓住單元格的detailTextLabel,我認爲這可能會導致問題。 –

+0

它爲什麼會崩潰?你在抓取單元格的detailTextLabel是爲了什麼? – EmilioPelaez

+0

,因爲我想根據detailTextLabel高度調整單元格行高度。 –

1

可以使用

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) 
{ 
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; 
cell.textLabel.numberOfLines = 0; 
cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:15.0]; 
} 

設定高度細胞

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSString *cellText = @"Go get some text for your cell."; 
UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:15.0]; 
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT); 
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 

return labelSize.height + 20;//set as per your need 
} 
+0

這種方法在iOS 5上不起作用 –

相關問題