tableview动态算一次高度的方法

来源:互联网 发布:java电商项目简历 编辑:程序博客网 时间:2024/05/16 04:26
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section % 2 == 0) {
        static XLNShoppingCartTitleCell *cell = nil;
        static dispatch_once_t onceToken;
        //只会走一次
        dispatch_once(&onceToken, ^{
            cell = (XLNShoppingCartTitleCell *)[tableView dequeueReusableCellWithIdentifier:@"XLNShoppingCartTitleCell"];
        });
        CGFloat height = [cell calulateHeightWithtTitle:[self.dataSourceArray objectAtIndex:indexPath.section] desrip:[self.dataSourceArray objectAtIndex:indexPath.section]];
        
        return height;
    } else {
        static XLNShoppingCTableViewCell *cell = nil;
        static dispatch_once_t onceToken;
        //只会走一次
        dispatch_once(&onceToken, ^{
            cell = (XLNShoppingCTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"XLNShoppingCTableViewCell"];
        });
        CGFloat height = [cell calulateHeightWithtTitle:[self.dataSourceArray objectAtIndex:indexPath.section] desrip:[self.dataSourceArray objectAtIndex:indexPath.section]];
        
        return height;
    }
    
}


- (CGFloat)calulateHeightWithtTitle:(NSString*)title desrip:(NSString*)descrip
{
    //这里非常重要
    CGFloat preMaxWaith = [UIScreen mainScreen].bounds.size.width - 60;
    [self.detailLabel setPreferredMaxLayoutWidth:preMaxWaith];
    [self.titleLabel setText:title];
    //这也很重要
    [self.detailLabel layoutIfNeeded];
    [self.detailLabel setText:descrip];
    [self.contentView layoutIfNeeded];
    CGSize size = [self.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    //加1是关键
    return size.height+1.0f;
}


0 0
原创粉丝点击