Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic table cell height

Using the storyboard, I've created a custom cell for my table view, I've also created a custom class for it with all my properties.

Now, what would be the best way in making the cells height dynamic, where is the best way to do this? Should I do this in the custom class for the cell? Or in my table view controller?

I imagine it would make more sense to do this in the custom class, but then how should I do this? Once a specific label is filled in, it should change the height of the cell

like image 306
woutr_be Avatar asked Jan 17 '23 19:01

woutr_be


2 Answers

You cannot change the height of the cell from your custom drawing class.

You can do this in the viewController that has the UITableView only. Either by specifying a hardcoded row height for all cells, or by using the

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

and specifying a height for the cells here. If you want to have different heights for the cells, you should check the indexpath.row property and return the desired height value.

In case you want to change the height of an already drawn in screen cell, you will have to reload that cell to reflect the change using this:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

like image 76
Lefteris Avatar answered Jan 28 '23 08:01

Lefteris


Use the following code

-(CGFloat)heightForText:(NSString *)str width:(int)width font:(UIFont *)font lineBreakMode:(NSLineBreakMode) lineBreakMode
{
    CGSize textSize;
    textSize = [str boundingRectWithSize:CGSizeMake(width, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : font} context:nil].size;
    return textSize.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == self.yourTable)
    {
            NSMutableDictionary *dict = [self.yourArray objectAtIndex:indexPath.row] ;
            return [self heightForText:[dict valueForKey:@"reviewDescription"] width:300 font:[UIFont fontWithName:kAppRegularFont size:15.0] lineBreakMode:0]+75;
    }
    return 70;
}
like image 39
Vikas Grandhi Avatar answered Jan 28 '23 08:01

Vikas Grandhi