Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView gaps when using dynamic row height

I have a UITableView of height 400px which I want to fill with either 10 or 11 custom UITableViewCells depending on the data to be displayed. The problem is that depending on how I set the height of each row using my current method, there are gaps between cells or below the bottom cell. I assume this is due to rounding.

This code puts scattered 1px gaps at the end of some of the cells:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {  
    if (isWednesdaySchedule) {
        return (tableView.frame.size.height/11);
    }
    else {
        return (tableView.frame.size.height/10);
    }
}  

And this code, with the returns casted to NSIntegers, makes all the cells fit together but leaves a gap of a few pixels below the bottom cell:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {  
    if (isWednesdaySchedule) {
        return (NSInteger)(tableView.frame.size.height/11);
    }
    else {
        return (NSInteger)(tableView.frame.size.height/10);
    }
}  

How can I fix this so that all of my cells display with no gaps in between or below the last cell?

like image 351
Arman Avatar asked Mar 07 '26 00:03

Arman


2 Answers

Well, you're only going to see a gapless table if the bounds of the table happens to be evenly divisible by 10 or 11. Tables are designed with the assumption that the rows will scroll off the screen so they try to fill the screen.

I think you have two options:

(1) Set the row height such that the bottom row is halfway off screen. The user will scroll up to see the last row and no obvious gap will exist between rows. There will be dead space at the end but users expect that in a table.

(2) Use section header and footer views to visually pad the space at the top and bottom of a single section to position it as you would like. I'm pretty sure you can use an empty transparent view of arbitrary height to center the section as you would like.

like image 83
TechZen Avatar answered Mar 09 '26 13:03

TechZen


If you don't actually need the cells to have different heights, why don't you just change the height of the UITableView depending on isWednesdaySchedule? This should fix the problems you mentioned.

like image 41
Dimitris Avatar answered Mar 09 '26 14:03

Dimitris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!