centred

Vertically Centred Cells in UITableView

I designed an app a couple of weeks ago with a table view and the cells were centred vertically.
Then after revisiting the design with an aim to put it into production I realised that there was no easy way to achieve this out of the box, so I made it my mission to find a flexible and reusable way to get this functionality.

First I decided to research to see if there was anything out there I could use with minimal effort.
There wasn’t.
However, I did gain an insight into a couple of ways I could do this.

The first one was a UITableView with a dynamic height and depending on the size of the dataSource, the tableview itself would be resized and repositioned up to a specified maximum.

The second option involved using the adjusting the height of the first section.
This option seemed a lot more dynamic, and easier to achieve than the first one, so I looked began thinking about creating a class to handle this.

The CentredTableView Class

Naturally, if I was going to play with the height of the sections, I’d need to process this logic within the - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section method.

I initially created a subclass of NSObject to handle this adjustment.

The two methods I created was an override of the method I mentioned earlier and one that could analyse the dataSource to determine a height for the table’s contents.

Both these methods depend on knowing what the height of a section is, and what the height of a cell is; so I created two definitions to hold these within the class.

A quick Google gave me those particular values, though they may not be wholly accurate. They are definitions so they can be adjusted if necessary.

I can now use my dataSource to calculate a total height for the table.

The returned value will add each cell’s height to each section’s height to give a total.

The Calculation of the Height

Now for the real meat of the subclass. The below method uses the datasource and the constants we’ve defined to calculate a header height for the first section header instance.

Implementation

Implementing this method is simple.
We just need to import our subclass and in the heightForHeaderInSection method, call our override.

The Final Files

You can download this subclass here CentredTableView (50)

Comments

comments

Powered by Facebook Comments