How to set UITableViewCell height based on screen size

I download data from the Internet, it consists of text and images. I put this data in a UITableView, and I want the image to be the background of the UITableViewCell. All images have the same resolution of 620x350.

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

What are the best solutions?

Thanks.

+5
source share
3 answers

Just 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 } 
+2
source

A BETTER and cleaner solution, just plays with the height of the cell , allowing you to automatically resize the image using Autolayout .

This is easy:

  • In your cell add a UIImageView and set the size you want to have when the cell has the actual height;

  • Set this UIImageView as a constraint, at least at the top, bottom, and one of the side border (right or left) ; also set restrictions on maintaining width / height ;

At this moment, when the cell grows, the image grows in height , and to maintain the proportion (thanks to the restriction), it changes the width , ALWAYS having the correct and proportional size.

Now you just have to write code for cell 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 ie 480 in iPhone 4*/; CGFloat factor = cellDefaultHeight/screenDefaultHeight return factor * [UIScreen mainScreen].bounds.size.height; } 

Obviously set the contentMode in the UIImageView to AspectFill .

+3
source

You can use the -tableView:heightForRowAtIndexPath: method in HTTableViewDelegate to return the height for each cell. In your case, you need something like this:

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return [UIScreen mainScreen].bounds.size.height; } 
-1
source

Source: https://habr.com/ru/post/1211795/


All Articles