UITableView spaces when using dynamic row height

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

This code places the scattered 1px spaces 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 returned data in NSIntegers makes all the cells fit together, but leaves 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 my cells are displayed without spaces between or below the last cell?

+3
3

, , 10 11. , , .

, :

(1) , . , , . , , .

(2) , , , . , , , .

+1

, UITableView isWednesdaySchedule? , .

+1

You can make the bottom cell a little larger to fill in the gap. If the difference in size is not large, it is probably not noticeable.

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

The code has not been tested, but I think you understand.

0
source

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


All Articles