UITableviewCell Label height changes in each reload

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

  1. erdinc27 macrumors regular

    Joined:
    Jul 20, 2011
    #1
    I created a custom UITableViewCell. Registered it like below
    Code:
    [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

    Code:
    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
    Code:
    - (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)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:@{NSFontAttributeName: font}
                                                 context:nil];
    
    return (rect.size.height + 20) < 56 ? 56 : (rect.size.height + 20);
    }
    
     
  2. PhoneyDeveloper macrumors 68040

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    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

    Joined:
    Jul 20, 2011
    #3
    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