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

前端 未结 10 1329
迷失自我
迷失自我 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:32

    as i searched over and over about this topic, finally this logic came to my thought. a simple code, but maybe not efficient enough, but so far it's the best i can find.

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
      NSDictionary * Object=[[NSDictionary alloc]init];
      Object=[Rentals objectAtIndex:indexPath.row];
      static NSString *CellIdentifier = @"RentalCell";
      RentalCell *cell = (RentalCell *)[tableView
                                      dequeueReusableCellWithIdentifier:CellIdentifier];
      if (cell == nil)
      {
          cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      }
       NSString* temp=[Object objectForKey:@"desc"];
       int lines= (temp.length/51)+1;
       //so maybe here, i count how many characters that fit in one line in this case 51
       CGRect correctSize=CGRectMake(cell.infoLabel.frame.origin.x, cell.infoLabel.frame.origin.y,    cell.infoLabel.frame.size.width, (15*lines));
       //15 (for new line height)
       [cell.infoLabel setFrame:correctSize];
       //manage your cell here
    }
    

    and here is the rest of the code

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
        NSDictionary * Object=[[NSDictionary alloc]init];
        Object=[Rentals objectAtIndex:indexPath.row];
        static NSString *CellIdentifier = @"RentalCell";
        RentalCell *cells = (RentalCell *)[tableView
                                      dequeueReusableCellWithIdentifier:CellIdentifier];
        NSString* temp=[Object objectForKey:@"desc"];
        int lines= temp.length/51;
    
        return (CGFloat) cells.bounds.size.height + (13*lines);
    }
    

提交回复
热议问题