Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set UITableViewCell height depending on screen size

I download data from the web, it consists of text and image. I'm putting this data into UITableView, and I want image to be a background of UITableViewCell. All the images has the same resolution 620x350.

All the iPhones have different screen sizes so I need to scale image's width and height depending on screen size,and also do this to UITableViewCell.

What are the best solutions?

Thank you.

like image 394
igrrik Avatar asked Jan 23 '15 21:01

igrrik


2 Answers

The BEST and clean solution, it is just playing with the height of the cell, letting the image be resized automatically by Autolayout.

It is easy:

  1. In your cell, add an UIImageView and set the size you want to have when the cell has the actual height;

  2. Set as constraints of this UIImageView, at least top, bottom and one of the lateral border (right or left); set also the constraints to keep the proportion width/height;

At this point, when the cell grow, the image grow in height, and to keep the proportion (thanks constraint) it is resized the width as well, having ALWAYS the correct and proportioned size.

Now therefore, you have just to write the code for the cell's height:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    static CGFloat cellDefaultHeight = /*the default height of the cell*/;
    static CGFloat screenDefaultHeight = /*the default height of the screen i.e. 480 in iPhone 4*/;

    CGFloat factor = cellDefaultHeight/screenDefaultHeight

    return factor * [UIScreen mainScreen].bounds.size.height;
}

Obviously, set the contentMode of the UIImageView to AspectFill.

like image 54
Matteo Gobbi Avatar answered Oct 14 '22 16:10

Matteo Gobbi


Simply use - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  CGFloat aspectRatio = 350.0f/620.0f;
   return aspectRatio * [UIScreen mainScreen].bounds.size.width;// assuming that the image will stretch across the width of the screen
}
like image 2
Bennie Avatar answered Oct 14 '22 18:10

Bennie