konturgestaltung
konturgestaltung

Reputation: 467

TableViewCell Height automatically adjusted to screen size

I have already implemented a tableView with my content needed. There are only 5 cells to be displayed. What I can't achieve right now is the following:

I want the five cells to be distributed evenly over the height of the tableview, dependend on the iphone used. So logically there should be a bigger height for an iPhone 5 than for the iphone 4. Also if there is retina or no retina there should be the correct distribution of the cells.

Do I have to provide different background images for that? and what would be the best approach for that:

the tableview looks like this:

[HEADER] [A - TEXT 1] [B - TEXT 2] [C - TEXT 3] [D - TEXT 4] [E - TEXT 5]

There should be no scrolling be possible at the end of day. Just automatically evenly distributed cells.

I am so glad for help on that...

thank you

Upvotes: 1

Views: 1232

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130193

First of all, if you can use the UITableViewDelegate method tableView:heightForRowAtIndexPath: to simple return the tables height divided by 5, which will make each cell a fifth of the tables height:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView bounds].size.height / (CGFloat)[myDataSourceArray count];
}

This will work for both iPhone 5 and iPhone 4 provided that you have configured the table to be the size of the screen. Furthermore, there is nothing you need to do to set the cells up for retina/non retina considering that when programming for iOS you specify screen dimensions in points not pixels which allows iOS to handle scaling automatically.

Then about the background images, there are a couple of different ways to do this depending on what end results you want. For example, if you just want to fill the cell with a pattern image and let the default table view separator divided them you can make an image in the minimum dimensions required to achieve the pattern. (could be 2x2px and 4x4 @2x) Then simply use:

[[cell contentView] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"myPatternImage"]]];

Or if you have an image with some sort of border that you wish to display around the cell, you could use a resizable image with cap insets to draw around the border and then fill the inside of the cell with a pattern, here's a screenshot to help explain how it works:

enter image description here

And then of course you could just add a UIImageView as a subview of the cell and add the full image to it which isn't exactly wrong, but I wouldn't recommend it because the other two ways I've suggested are more efficient. Hope this helps!

Upvotes: 5

Related Questions