2012-10-29 39 views
0

如何根據它們中的內容數量來擴展UITableViewCells?在我的單元格中,我使用了代表論壇的3個標籤。標籤被命名爲「別名」,「日期」和「評論」。第三個標籤評論,可以是任意數量的大小。因此,我的單元格需要根據「評論」標籤的大小動態變化。下面是我的相關代碼:定製UITableViewCell的高度

- (UITableViewCell *)tableView:(UITableView *)pTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *CellIdentifier = @"ForumthreadCell"; 
UITableViewCell *cell = [pTableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) 
{ 
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

Feedback *item = [self.items objectAtIndex:indexPath.row]; 

UILabel *aliasLabel = (UILabel *)[cell viewWithTag:1]; 
UILabel *commentLabel = (UILabel *)[cell viewWithTag:2]; 
UILabel *dateLabel = (UILabel *)[cell viewWithTag:3]; 

[aliasLabel setText:item.alias]; 
[commentLabel setText:item.comment]; 
[dateLabel setText:[self.dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:(double)item.time]]]; 

commentLabel.numberOfLines = 0; 
[commentLabel sizeToFit]; 

CGSize textHeight = [commentLabel.text sizeWithFont:commentLabel.font constrainedToSize:CGSizeMake(maxWidth, lineHeight * commentLabel.numberOfLines)lineBreakMode:UILineBreakModeWordWrap]; 

return cell; 
} 

正如你所看到的,我設定textHeight不同的commentsLabel的高度。但從現在開始我應該怎麼做?如果我知道標籤的高度,如何根據commentLabel的高度來設置單元的高度?請根據我的代碼給出代碼示例。我想我應該用下面的方法,但我不知道如何做到這一點:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

} 

回答

6

使用此方法來獲取文本的文字高度

-(CGFloat)getLabelHeightForText:(NSString *)text andWidth:(CGFloat)labelWidth 
{ 

CGSize maximumSize = CGSizeMake(labelWidth, 10000); 

//provide appropriate font and font size 
CGSize labelHeighSize = [text sizeWithFont: [UIFont fontWithName:@"Trebuchet MS" size:13.0f] 
         constrainedToSize:maximumSize 
          lineBreakMode:UILineBreakModeTailTruncation]; 
return labelHeighSize.height; 
} 

此方法將返回的高度你傳遞的文字。在你的課堂中添加這個方法。並使用的tableView:heightForRowAtIndexPath:委託方法來設置高度爲每個小區

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    Feedback *item = [self.items objectAtIndex:indexPath.row]; 

    CGFloat textHeight = [self getLabelHeightForText:item.comment andWidth:162];//give your label width here 
    return textHeight; 
}  

我覺得這個問題會得到解決。

+0

Thanx,這解決了我的問題!你終於解決了1天工作我,你是一個英雄! – user1293618

+0

嗨,我發現了一個新的問題,自定義單元格,因爲我使用你的代碼,我想看看你是否知道這件事?這裏是鏈接:http://stackoverflow.com/questions/13223682/my-cells-resize-after-scrolling-upwards /關心 –

0

你可以使標籤的聲明中的實現:

@implementation pTableView 
{ 
    UILabel *aliasLabel; 
} 

然後在行的高度,你可以使用默認的高度(44)+ aliasLabel.Height

return 44 + aliasLabel.frame.size.height; 

然後,如果你需要區分您的表中的標籤

aliasLabel.tag = indexpath.row