使用tableview单元格中的labet文本扩展单元格高度

时间:2016-10-25 09:54:00

标签: ios7

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

NSString * message =[[chatData objectAtIndex:indexPath.row]valueForKey:@"message"];
NSString * message_type = [[chatData objectAtIndex:indexPath.row]valueForKey:@"message_type"];

if([[[chatData objectAtIndex:indexPath.row]valueForKey:@"message_type"] isEqualToString:@"0"]){
    CGSize sizeText = [self text:message sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds) - 100, 9999) withLinebreakmode:NSLineBreakByWordWrapping];
    CGFloat heightOfRow = sizeText.height + 2 * 7.5f;
    return heightOfRow + 50;
}
else
    return 225;//message_type 1 3 4

//    return self.chatTable.rowHeight;

}

pragma mark - 处理ChatLabel宽度

- (CGSize)text:(NSString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)ConstSize withLinebreakmode:(NSLineBreakMode)linebreakmode {     CGSize retsize;

if ([text respondsToSelector:@selector(boundingRectWithSize:options:attributes:context:)])
{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = linebreakmode;
    //  paragraphStyle.alignment = NSTextAlignmentLeft;
    NSDictionary * attributes = @{NSFontAttributeName : font,NSParagraphStyleAttributeName : paragraphStyle};
    retsize = [text boundingRectWithSize:ConstSize options:NSStringDrawingUsesFontLeading
               |NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
    retsize.height =ceilf(retsize.height);
    retsize.width =ceilf(retsize.width);

    NSLog(@"%f",retsize.width);


}else{

    if ([text respondsToSelector:@selector(sizeWithFont:constrainedToSize:lineBreakMode:)]){
        retsize = [text sizeWithFont:font
                   constrainedToSize:ConstSize
                       lineBreakMode:linebreakmode];
        retsize = [text boundingRectWithSize:ConstSize options:NSStringDrawingUsesLineFragmentOrigin attributes:nil context:nil].size;
    }
}
//[self viewWillAppear:YES];
return retsize;

}

1 个答案:

答案 0 :(得分:0)

试试这段代码。

1.如果您使用此代码,则应仅为标签提供顶部,底部,左侧和右侧约束。

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    //Here you give a minimum height of the cell size.
    return 110;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}