How can I do variable height table cells on the iPhone properly?

前端 未结 3 1898
时光取名叫无心
时光取名叫无心 2020-12-12 19:56

My app needs to have variable height table cells (as in each table cell differs in height, not that each cell needs to be able to resize itself).

I have a solution t

3条回答
  •  -上瘾入骨i
    2020-12-12 20:21

    I realise this won't work for you due to the infinite loop you mention, but I've had some success with calling the cells layoutSubViews method

    Though this may be a little inefficient due to multiple calls to both cellForRowAtIndexPath and layoutSubViews, I find the code is cleaner.

    -(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        MyCell *cell = (MyCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    
        [cell layoutSubviews];
    
        return CGRectGetHeight(cell.frame);
    }
    

    And in the layout code:

    - (void)layoutSubviews
    {
        [super layoutSubviews];
    
        //First expand the label to a large height to so sizeToFit isn't constrained
        [self.myArbitrarilyLengthLabel setFrame:CGRectMake(self.myArbitrarilyLengthLabel.frame.origin.x,
                                              self.myArbitrarilyLengthLabel.frame.origin.y,
                                              self.myArbitrarilyLengthLabel.frame.size.width,
                                              1000)];
    
    
        //let sizeToFit do its magic
        [self.myArbitrarilyLengthLabel sizeToFit];
    
        //resize the cell to encompass the newly expanded label
        [self setFrame:CGRectMake(self.frame.origin.x,
                                 self.frame.origin.y,
                                 self.frame.size.width,
                                  CGRectGetMaxY(self.myArbitrarilyLengthLabel.frame) + 10)];
    }
    

提交回复
热议问题