如何在iOS中设置UITableView自定义单元格的高度?

时间:2015-12-09 08:02:51

标签: ios xcode uitableview

我正在尝试制作一个消息传递应用。我有一个tableview,我必须添加来自JSON webservice的所有消息。我正在使用从UITalbeViewCell继承的自定义类来定制单元格。

我没有这个自定义类的任何nib文件。我只创建此类的对象并设置其消息标签文本并在“cellForRowAtIndexPath”委托方法中作为单元格返回。

现在我遇到一个问题,即自定义类根据消息的长度返回完美的布局消息单元格,并且它的高度也很完美但是当这个单元格在UITableView中添加时,行的高度不会自动设置为高度自定义单元格的大小,这就是为什么较大的文本单元格重叠。请帮助我,我可以如何设置自定义单元格的高度。

您可以看到细胞重叠的错误图像

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要计算每个单元格的高度heightForRowAtIndexPath委托方法并返回该值,如下所示

- (CGFloat)tableView:(HBTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
     CGRect textRect = [<YOUR_MESSAGE> boundingRectWithSize:boundingSize options:NSStringDrawingUsesFontLeading attributes: @{NSFontAttributeName:<LABEL_FONT>} context:nil];
     return textRect.size.height + <PADDING_LABEL>;
     //PADDING_LABEL = CELL_DEFAULT_HEIGHT-LABEL_DEFAULT_HEIGHT
}

答案 1 :(得分:0)

实现此方法并在返回之前根据文本长度计算行高。

(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   NSInteger nofLines;
   nofLines = [self getNOFLinesForLabel:296 usingFont:font forText:fullDescription];
   return nofLines*13;
}

-(NSInteger) getNOFLinesForLabel:(CGFloat)width usingFont:(UIFont *)font forText:(NSString *)text {


    CGRect rect = [text boundingRectWithSize:CGSizeMake(200, MAXFLOAT)
                                     options:NSStringDrawingUsesLineFragmentOrigin
                                  attributes:@{NSFontAttributeName : font}
                                     context:nil];

    return ceil(rect.size.height / font.lineHeight);
}

调整标签宽度,字体大小和其他参数,它将开始正常工作。