2010-02-24 36 views
0

我有一個不同條目的表,每個條目的長度都不相同。每行的高度應該適合,因此它可以顯示整個字符串。如何根據Stringlength更改TableViewCell的rowHeight

我使用下面的代碼:

//... cellForRowAtIndexPath 
if (row == 0) { 

    cell = [tableView dequeueReusableCellWithIdentifier:@"affCell"]; 
    //if (!cell) { 
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"affCell"]autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryNone; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cell.autoresizingMask = UIViewAutoresizingFlexibleHeight; 

    affL = [[UILabel alloc] initWithFrame:CGRectZero]; 
    affL.textAlignment = UITextAlignmentLeft; 
    affL.autoresizingMask = UIViewAutoresizingFlexibleHeight; 
    [cell.contentView addSubview:affL]; 
    //} 
    //declaration label 
    affL.text = [fDictionary objectForKey:@"aff"]; 
    affL.numberOfLines = 0; 
    [affL sizeToFit]; 
    affL.frame = CGRectMake(15.0, 10.0, 220.0, affL.frame.size.height); 
    CGFloat affLH = affL.frame.size.height; 
    [tableView setRowHeight:affLH+30]; 

我也用

//... heightForRowAtIndexPath 

return affL.frame.size.height; 

我怎樣才能解決這個問題呢?

回答

0

In -heightForRowAtIndexPath你必須測量字符串在你需要的字體大小(使用像 - sizeWithFont:constrainedToSize:lineBreakMode :)並返回你需要的高度。

+0

好吧,仔細看看..你仔細檢查你的-dequeueReusableCellWithIdentifier是否爲零,對不對?如果不是零,你想重用它來獲得更好的性能。它將已經包含一個UILabel。如果每個單元格的高度不同,則可能不需要每次調用[tableView setRowHeight:]時調用-cellForRowAtIndexPath。 In - heightForRowAtIndexPath返回的UILabel的高度可以工作,否則嘗試[myString sizeWithFont:affL.font constrainedToSize:CGSizeMake(affL.frame.size.width,CGFLOAT_MAX)] – 2010-02-24 13:16:47

+0

我想我不需要添加標籤。看到我下面的新代碼。 – 2010-02-24 14:49:45

0

我想我不需要添加到單元格的標籤,因爲單元格只包含一個字符串。

所以我改變了代碼:

//... heightForRow... 

NSString *myText = [myDictionary objectForKey:@"affirmation"]; 

return [myText sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize: 
CGSizeMake(220.0, CGFLOAT_MAX) /* 220 = width of Cell */ lineBreakMode:UILineBreakModeWordWrap].height; 

//... cellForRow... 

cell = [tableView dequeueReusableCellWithIdentifier:@"affirmationCell"]; 
if (cell == nil) 
{ 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"affirmationCell"]autorelease]; 
    cell.accessoryType = UITableViewCellAccessoryNone; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    cell.autoresizingMask = UIViewAutoresizingFlexibleHeight; 
} 

cell.textLabel.text = [myDictionary objectForKey:@"myAff"]; 

return cell; 

但它不工作。出了什麼問題?

+0

我修好了!必須添加一個默認值到高度 return [...] height + 44.0; – 2010-02-24 15:03:18

+0

非常感謝您的幫助。 – 2010-02-24 15:04:29

+0

「return」語句運行後沒有任何東西。函數或方法返回時停止執行。 – 2010-02-26 12:42:15