如何在iPhone中包含可变长度的图像作为UITableViewCell背景?

问题描述:

我必须包括一个气泡,如附图所示,作为表格视图单元格中的背景。如何在iPhone中包含可变长度的图像作为UITableViewCell背景?

enter image description here

但泡沫继续基于文本的长度,高度变化的。什么是实施这个最好的方法?

您需要根据文本长度来计算单元格高度,我通常在我自定义的UITableViewCell中做一个类方法。

+ (CGFloat)cellHeightForText:(NSString *)text 
{ 
    CGFloat cellHeight = 0.0; 

    // calculate cellHeight height according to text length 

    // here you set the maximum width and height you want the text to be 
    CGSize maxSize = CGSizeMake(kTextMaxWidth, kTextMaxHeight); 

    CGSize size = [text sizeWithFont:TEXT_FONT 
         constrainedToSize:maxSize 
          lineBreakMode:UILineBreakModeWordWrap]; 

    // set some minimum height for the cell (if the text is too short..) 
    cellHeight = MAX(size.height, kMinHeight); 

    // here I usually increase the cellHeight according to the cell's other subviews 
    // because if you have other subviews under/above the bubble you need to count them 
    // and add height to the cell... 
    cellHeight += kSomeSpaceToAdd; 

    return cellHeight; 
} 

则U根据文本长度调用此方法heightForRowAtIndexPath

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    Message *currMessage = [self.myMessages objectAtIndex:indexPath.row]; 

    CGFloat height = [MyCustomCell cellHeightForText:currMessage.text]; 

    return height; 
} 

当然,你也应该设置泡沫图像帧,我的东西做这个自定义单元格layoutSubviews方法,在这指向已设置的单元格高度,以便您可以使用它(self.bounds.size.height)来相应地设置您的气泡图像。