UITableviewCell Label height changes in each reload

Discussion in 'iOS Programming' started by erdinc27, Mar 24, 2017.

  1. erdinc27 macrumors regular

    Jul 20, 2011
    I created a custom UITableViewCell. Registered it like below
    [self.mainTableView registerNib:[UINib nibWithNibName:@"MainTableCell" bundle:nil] forCellReuseIdentifier:@"mainTableCell"];
    When an imageView pressed inside of that cell then I refresh the data and reload the cell only not all tableView. But there is a weird problem which is whenever I reload the cell then a UILabel inside starts to shrink in every reload. This is how I reload the data

    NSIndexPath *path = [NSIndexPath indexPathForRow:gesture.view.tag inSection:0];
    MainTableCell *cell = [self.mainTableView cellForRowAtIndexPath:path];
    [self.mainTableView reloadRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationNone];
    And this is how the cell size is calculated
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Post *post = self.posts[indexPath.row];
    NSString *text = post.text;   
    UIFont *font = [UIFont systemFontOfSize:20];
    CGRect rect = [text boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX)
                                              attributes:@{NSFontAttributeName: font}
    return (rect.size.height + 20) < 56 ? 56 : (rect.size.height + 20);
  2. PhoneyDeveloper macrumors 68040


    Sep 2, 2008
    I don't see anything obviously wrong in your code. You need to verify that the font is correct and the label width is correct. The code you show sets the height of the cell, not the height of the label. You don't mention how that's set.

    I've given up using heightForRowAtIndexPath in favor of self-sizing cells. While auto layout can be complicated it avoids calculating the rowHeight manually like this.
  3. erdinc27 thread starter macrumors regular

    Jul 20, 2011
    in our company my boss doesnt want me to use auto layout. I found the error after your explanation. I calculated label frame in cellforRowAtIndexPath method. I fixed it and it works well now.

Share This Page