how to get a UITableView row height to auto-size to the size of the UITableViewCell?

前端 未结 5 832
梦谈多话
梦谈多话 2020-12-23 17:24

How to get a UITableView row height to auto-size to the size of the UITableViewCell?

So assuming I\'m creating the UITableViewCell in Interface Builder, and it hei

5条回答
  •  时光取名叫无心
    2020-12-23 18:15

    http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/ is a great tutorial for this.

    The main bit is

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
    {
      // Get the text so we can measure it
      NSString *text = [items objectAtIndex:[indexPath row]];
      // Get a CGSize for the width and, effectively, unlimited height
      CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
      // Get the size of the text given the CGSize we just made as a constraint
      CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
      // Get the height of our measurement, with a minimum of 44 (standard cell size)
      CGFloat height = MAX(size.height, 44.0f);
      // return the height, with a bit of extra padding in
      return height + (CELL_CONTENT_MARGIN * 2);
    }
    

提交回复
热议问题