iOS2013. 6. 25. 18:54

This sample code shows how we can create uitableviewcell height dynamically based on the text it consists.
Let assume we have UILabel in cell which contains some text, and code below  creates the appropriate cell in tableview depending on the label size :

1. Lets define some constants for the program:
      #define FONT_SIZE 14.0f
      #define CELL_CONTENT_WIDTH  305.0f
      #define CELL_CONTENT_MARGIN  8.0f

2. Return the height of each cell depending on its label size : 

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
        NSString *text =@"Read your text for each cell here (from Array or Dictionary)";
         // calculating the size of the text/string
        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
  
         // Calculating the height of cell
              CGFloat height = MAX(size.height, 44.0f);
              return height + (CELL_CONTENT_MARGIN * 2);

}

3.  Now lets create cell having UILabel init:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
    }
// Below two line code will insure that there will be no overlapping/blurr of custom views created inside cell
    for (UIView * view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }


          NSString *text = @"Read your text for each cell here (from Array or Dictionary)";
          UILabel *descriptionLabel = [[UILabel alloc] initWithFrame: CGRectMake(10, 8, 278, 40)];
          // 40 choose the height of label double of normal label size
           descriptionLabel.adjustsFontSizeToFitWidth = NO;
           descriptionLabel.text = text;
             [cell.contentView addSubview:descriptionLabel];
             [descriptionLabel setNumberOfLines:0];
           CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
           CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
           [descriptionLabel setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];

 return cell;
    
}

Posted by 다오나무