Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios TableView different cell height

Tags:

ios

tableview

I am working on an app which requires me to show pictures and some text in TableView. These pictures can be of different heights and so I need to vary the cell height accordingly. so I have overridden this method :

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

If I have a single static value for cell identifier then the height of the image inside the cell cannot vary dynamically.

So do I need to have different values of Cell Identifier for each cell ? Is there some other way ?

I cannot use some other view than Tableview because I need to show some cells dynamically in between based on user interaction.

Thanks.

like image 690
user1060418 Avatar asked Oct 20 '22 17:10

user1060418


1 Answers

You should reference your data model to get the image size and return the row height.

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
        UIImage *image = dataModel[indexPath.row];
        return image.size.height + 16.0; //16 is for padding
}

If you subclass your cell, you can adjust the imageView frame in -layoutsubviews (after super):

- (void)setupImageView
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    imageView.clipsToBounds = YES;
    self.contentImageView = imageView;

    [self.contentView addSubview:imageView];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    CGRect bounds = self.contentView.bounds;
    float margin = 8.0;
    CGRect textViewFrame = CGRectZero;
    textViewFrame = CGRectMake(margin, roundf(margin * 2.0), bounds.size.width - (margin * 2.0), roundf(bounds.size.height - (margin * 4.0)));

    self.contentImageView.frame = textViewFrame;
}
like image 181
Hobbes the Tige Avatar answered Nov 01 '22 19:11

Hobbes the Tige