0

Im trying to make dynamic uitableviewcell height for my custome cell.

the cell is subclassed for adding some background.

this is my uitableview controller class :

#define PADDING  23.0f

- (void)viewDidLoad
{

    [super viewDidLoad];

    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger count = [self.entries count];

    return count + _rowcount;
} 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *reuseIdentifier = @"PlaceholderCell2";
    SubcategoryTableViewCell * sctvCell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (sctvCell == nil) {


        sctvCell= [[SubcategoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];

    }
    NSUInteger nodeCount = [self.entries count];
    sctvCell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    UILabel *label = (UILabel *)[sctvCell.contentView viewWithTag:1];
    if (nodeCount > 0)
    {


        NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];

        [label setText:appRecord.title];

        NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"B MyFont" size:14.0f]};

        CGRect rect = [appRecord.title boundingRectWithSize:CGSizeMake(label.frame.size.height - PADDING * 5, MAXFLOAT)
                                                    options:NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:attributes
                                                    context:nil];
        CGRect newFrame = label.frame;
        newFrame.size.height = rect.size.height;

        label.frame = newFrame;
        [label sizeToFit];

        UIView *whiteRoundedCornerView = (UIView *)[sctvCell.contentView viewWithTag:1000];
        CGRect newFrame2 =  whiteRoundedCornerView.frame;
        newFrame2.size.width = 300;
        newFrame2.size.height = rect.size.height + 160;
        [ whiteRoundedCornerView setFrame:newFrame2];

    }

        if ((unsigned long)indexPath.row == [self.entries count] - 1){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
                       ^{
                           NewsFetchParseOperation *p = [[NewsFetchParseOperation alloc]init];
                           NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
                           p.cat = appRecord.Category;
                           self.intindex = self.intindex + 1;
                           p.index = [NSString stringWithFormat:@"%d", (int)self.intindex];
                           p.lastid = appRecord.ids;
                           [p main];
                           dispatch_async(dispatch_get_main_queue(), ^(void)
                                          {

                                               [self.tableView beginUpdates];
                                                   NSMutableArray *indexPaths = [NSMutableArray array];
                                                   NSInteger currentCount = self.entries.count;
                                                   for (NSUInteger i = 0; i < p.appRecordList.count; i++) {
                                                       [indexPaths addObject:[NSIndexPath indexPathForRow:currentCount+i inSection:0]];
                                                   }
                                              NSArray *temp_1 =[self.entries arrayByAddingObjectsFromArray:p.appRecordList];
                                              self.entries = temp_1;
                                              [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationLeft];
                                              [self.tableView endUpdates];

                                          });
                       });
    }
    return sctvCell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *reuseIdentifier = @"PlaceholderCell2";
    SubcategoryTableViewCell * sctvCell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (sctvCell == nil) {


        sctvCell= [[SubcategoryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];

    }

        NewsFetchAppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
        UILabel *label = (UILabel *)[sctvCell.contentView viewWithTag:1];
        NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"B MyFont" size:14.0f]};
        CGRect rect = [appRecord.title boundingRectWithSize:CGSizeMake(label.frame.size.height - PADDING * 5, MAXFLOAT)
                                              options:NSStringDrawingUsesLineFragmentOrigin
                                           attributes:attributes
                                              context:nil];


        return rect.size.height + PADDING * 6;

}

and my cell subclass :

- (void)awakeFromNib {
    self.news_img.layer.cornerRadius = 4;
    self.news_img.clipsToBounds = YES;
    self.resource_icon_img.layer.cornerRadius = 4;
    self.resource_icon_img.clipsToBounds = YES;
    self.contentView.backgroundColor = [UIColor clearColor];
    self.whiteroundcorner = [[UIView alloc] initWithFrame:CGRectMake(10,10,300,250)];
    self.whiteroundcorner.backgroundColor = [UIColor whiteColor];
    self.whiteroundcorner.layer.masksToBounds = NO;
    self.whiteroundcorner.layer.cornerRadius = 3.0;
    [self.whiteroundcorner.layer setShadowColor:[UIColor grayColor].CGColor];
    self.whiteroundcorner.layer.shadowOffset = CGSizeMake(-1, 1);
    self.whiteroundcorner.layer.shadowOpacity = 0.2;
    self.whiteroundcorner.tag = 1000;
    [self.contentView addSubview:self.whiteroundcorner];
    [self.contentView sendSubviewToBack:self.whiteroundcorner];
}

im using story board for my table like this :

enter image description here

now problem is most of time the height calculated incorrectly.

also some time the height goes way beyond on cell and in the end of 10 cell

when i try to fetch new row the last cell apears incorrectly.

Ahad Porkar
  • 1,666
  • 2
  • 33
  • 68

1 Answers1

0

You will need to calculate the height for the cell after setting its content.

So something like this:

    - (CGFloat)heightForCellAtIndexPath:(NSIndexPath *)indexPath {

        static UITableViewCell *sizingCell = nil;
        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            sizingCell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        });

/* Method where you set the content of the cell */ 

        [self configureCell: atIndexPath:indexPath];
        return [self calculateHeightForConfiguredSizingCell:sizingCell];
    }


    - (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {

        [sizingCell setNeedsDisplay];
        [sizingCell layoutIfNeeded];

        CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        return size.height;
    }
Robert J. Clegg
  • 7,231
  • 9
  • 47
  • 99