kai Taylor kai Taylor - 4 months ago 70
iOS Question

How to populate UITableView from the bottom upwards?

is it possible to reverse the order of a tableView. I have searched a lot for a solution but all the results have not quite been a solution to what I am trying to achieve. They all suggest scrolling to the last position of a table with

scrollToRowAtIndexPath
and populating the data in reverse. But this doesn't work if the table content is dynamic and in some instances not all the cells have data. For example in a normal tableView the order is:




label 1



label 2



label 3



empty



empty



scroll direction

v

V





the desired result would be:

scroll direction

^

^


empty



empty



empty



label 3



label 2



label 1






in this example if I used the suggested method of
scrollToRowAtIndexPath
and use the length of the array of objects, I would only get the third cell from the top. And end up with something like this:




unwanted outcome:

label 3



label 2



label 1



empty



empty



scroll direction

v

V





any help would be great thank you.

Answer

To populate table from the bottom use this:

- (void)updateTableContentInset {
    NSInteger numRows = [self tableView:self.tableView numberOfRowsInSection:0];
    CGFloat contentInsetTop = self.tableView.bounds.size.height;
    for (NSInteger i = 0; i < numRows; i++) {
        contentInsetTop -= [self tableView:self.tableView heightForRowAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        if (contentInsetTop <= 0) {
            contentInsetTop = 0;
            break;
        }
    }
    self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0);
}

To reverse order of elements use this:

dataSourceArray = dataSourceArray.reverseObjectEnumerator.allObjects;

Swift version:

func updateTableContentInset() {
    var numRows = self.tableView(self.tableView, numberOfRowsInSection: 0)
    var contentInsetTop = self.tableView.bounds.size.height
    for i in 0 ..< numRows {
        contentInsetTop -= self.tableView(self.tableView, heightForRowAtIndexPath:NSIndexPath(forItem: i, inSection: 0))
        if contentInsetTop <= 0 {
            contentInsetTop = 0
        }
    }
    self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0)
}