Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView with different cell prototypes and heights using Storyboards

I am currently working on my first iOS application and just ran into an issue that I can't seem to solve. After long hours of thought and struggle, I decided to ask here to see if someone has ran into a similar issue and can help me.

I have a UITableView with two cell prototypes. I am able to render both cell types without a problem but there is a small catch. One cell type has a height of 475px while the other one only 250px. When the table view gets rendered, every row of the table has the same height. I went ahead and debugged my storyboard and found that my table view has a row height of 475px. This is fine for the taller cell, but for the small ones it leaves a blank space in between.

I would like to be able to adjust the height of each row depending on what type of cell it is being rendered. Is this possible? I was thinking about using the heightForRowAtIndexPath, but because at the moment of execution cells don't exists I cannot check what is the class of the cell at a certain index. Also, in my storyboard I specified the height for each of the two cell prototypes, but it is not reflected at runtime. Does anyone have an idea how to solve this kind of problem? Thank you in advanced.

like image 211
Daniel Garzon Avatar asked Mar 20 '23 05:03

Daniel Garzon


1 Answers

You need to use heightForRowAtIndexPath but you shouldn't be inspecting the table to find out which cell is in which index. You should be inspecting your datasource.

For instance, in cellForRowAtIndexPath you will have something like...

if ( /*some condition*/ ) {
    cell = //dequeue cell type 1
} else {
    cell = //dequeue cell type 2
}

So, in heightForRow you do exactly the same check.

if ( /*some condition*/ ) {
    return 475;
} else {
    return 250;
}
like image 54
Fogmeister Avatar answered Apr 24 '23 21:04

Fogmeister