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.
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:
In your cell, add an UIImageView
and set the size you want to have when the cell has the actual height;
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
.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With