Iphone - when to calculate heightForRowAtIndexPath for a tableview when each cell height is dynamic?

前端 未结 10 1289
迷失自我
迷失自我 2020-11-30 19:50

I have seen this question asked many times but astoundingly, I have not seen a consistent answer, so I will give it a try myself:

If you have a tableview containing

10条回答
  •  独厮守ぢ
    2020-11-30 20:23

    This is how I calculate the height of a cell based on the amount of text in a UTextView:

    #define PADDING  21.0f
    
    - (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        if(indexPath.section == 0 && indexPath.row == 0)
        {   
            NSString *practiceText = [practiceItem objectForKey:@"Practice"];
            CGSize practiceSize = [practiceText sizeWithFont:[UIFont systemFontOfSize:14.0f] 
                       constrainedToSize:CGSizeMake(tblPractice.frame.size.width - PADDING * 3, 1000.0f)];
            return practiceSize.height + PADDING * 3;
        }
    
        return 72;
    }
    

    Of course, you would need to adjust the PADDING and other variables to fit your needs, but this sets the height of the cell which has a UITextView in it, based on the amount of text supplied. so if there are only 3 lines of text, the cell is fairly short, where as if there are 14 lines of text, the cell is rather large in height.

提交回复
热议问题