How to position UITableViewCell at bottom of screen?

12,610

Solution 1

I've create a new sample solution since the previous answer is not outdated for modern use.

The latest technique uses autolayout and self-sizing cells so the previous answer would no longer work. I reworked the solution to work with the modern features and created a sample project to put on GitHub.

Instead of counting up the height of each row, which is causes additional work, this code instead gets the frame for the last row so that the content inset from the top can be calculated. It leverages what the table view is already doing so no additional work is necessary.

This code also only sets the top inset in case the bottom inset is set for the keyboard or another overlay.

Please report any bugs or submit improvements on GitHub and I will update this sample.

GitHub: https://github.com/brennanMKE/BottomTable

- (void)updateContentInsetForTableView:(UITableView *)tableView animated:(BOOL)animated {
    NSUInteger lastRow = [self tableView:tableView numberOfRowsInSection:0];
    NSUInteger lastIndex = lastRow > 0 ? lastRow - 1 : 0;

    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:lastIndex inSection:0];
    CGRect lastCellFrame = [self.tableView rectForRowAtIndexPath:lastIndexPath];

    // top inset = table view height - top position of last cell - last cell height
    CGFloat topInset = MAX(CGRectGetHeight(self.tableView.frame) - lastCellFrame.origin.y - CGRectGetHeight(lastCellFrame), 0);

    UIEdgeInsets contentInset = tableView.contentInset;
    contentInset.top = topInset;

    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState;
    [UIView animateWithDuration:animated ? 0.25 : 0.0 delay:0.0 options:options animations:^{
        tableView.contentInset = contentInset;
    } completion:^(BOOL finished) {
    }];
}

Solution 2

Call this method whenever a row is added:

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

Solution 3

You can set a header in your table view and make it tall enough to push the first cell down. Then set the contentOffset of your tableView accordingly. I don't think there is a quick built in way to do this though.

Solution 4

I didn't like empty-cell, contentInset or transform based solutions, instead I came up with other solution:

Example

UITableView's layout is private and subject to change if Apple desires, it's better to have full control thus making your code future-proof and more flexible. I switched to UICollectionView and implemented special layout based on UICollectionViewFlowLayout for that (Swift 3):

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    // Do we need to stick cells to the bottom or not
    var shiftDownNeeded = false

    // Size of all cells without modifications
    let allContentSize = super.collectionViewContentSize()

    // If there are not enough cells to fill collection view vertically we shift them down
    let diff = self.collectionView!.bounds.size.height - allContentSize.height
    if Double(diff) > DBL_EPSILON {
        shiftDownNeeded = true
    }

    // Ask for common attributes
    let attributes = super.layoutAttributesForElements(in: rect)

    if let attributes = attributes {
        if shiftDownNeeded {
            for element in attributes {
                let frame = element.frame;
                // shift all the cells down by the difference of heights
                element.frame = frame.offsetBy(dx: 0, dy: diff);
            }
        }
    }

    return attributes;
}

It works pretty well for my cases and, obviously, may be optimized by somehow caching content size height. Also, I'm not sure how will that perform without optimizations on big datasets, I didn't test that. I've put together sample project with demo: MDBottomSnappingCells.

Here is Objective-C version:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;
{
    // Do we need to stick cells to the bottom or not
    BOOL shiftDownNeeded = NO;

    // Size of all cells without modifications
    CGSize allContentSize = [super collectionViewContentSize];

    // If there are not enough cells to fill collection view vertically we shift them down
    CGFloat diff = self.collectionView.bounds.size.height - allContentSize.height;
    if(diff > DBL_EPSILON)
    {
        shiftDownNeeded = YES;
    }

    // Ask for common attributes
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    if(shiftDownNeeded)
    {
        for(UICollectionViewLayoutAttributes *element in attributes)
        {
            CGRect frame = element.frame;
            // shift all the cells down by the difference of heights
            element.frame = CGRectOffset(frame, 0, diff);
        }
    }

    return attributes;
}

Solution 5

Here is the Swift 3 version of the @Brennan accepted solution, tested and approved :)

func updateContentInsetForTableView( tableView:UITableView,animated:Bool) {

    let lastRow = tableView.numberOfRows(inSection: 0)
    let lastIndex = lastRow > 0 ? lastRow - 1 : 0;

    let lastIndexPath = IndexPath(row: lastIndex, section: 9)


    let lastCellFrame = tableView.rectForRow(at: lastIndexPath)
    let topInset = max(tableView.frame.height - lastCellFrame.origin.y - lastCellFrame.height, 0)

    var contentInset = tableView.contentInset;
    contentInset.top = topInset;

    _ = UIViewAnimationOptions.beginFromCurrentState;
        UIView.animate(withDuration: 0.1, animations: { () -> Void in

    tableView.contentInset = contentInset;
   })

   } 
Share:
12,610

Related videos on Youtube

ohho
Author by

ohho

I run and write code.

Updated on March 30, 2020

Comments

  • ohho
    ohho about 4 years

    There are one to three UITableViewCells in a UITableViewView. Is there a way to always position the cell(s) at the bottom of screen after reloadData?

    +----------------+     +----------------+     +----------------+
    |                |     |                |     |                |
    |                |     |                |     |                |
    |                |     |                |     |                |
    |                |     |                |     | +------------+ |
    |                |     |                |     | |   cell 1   | |
    |                |     |                |     | +------------+ |
    |                |     | +------------+ |     | +------------+ |
    |                |     | |   cell 1   | |     | |   cell 2   | |
    |                |     | +------------+ |     | +------------+ |
    | +------------+ |     | +------------+ |     | +------------+ |
    | |   cell 1   | |     | |   cell 2   | |     | |   cell 3   | |
    | +------------+ |     | +------------+ |     | +------------+ |
    +----------------+     +----------------+     +----------------+
    
    • Espresso
      Espresso over 11 years
      Would scrolling be enabled?
    • ohho
      ohho over 11 years
      @Espresso scrolling does not matter as long as the last cell is at bottom
    • Nazik
      Nazik over 11 years
      Does the height of cell static?
    • ohho
      ohho over 11 years
      @NAZIK you may assume yes.
    • keji
      keji over 8 years
      You could always rotate the table upside down and then rotate the cells to counter that.
  • Mike D
    Mike D over 11 years
    @ohho In addition, you could make the table grouped.
  • RevanProdigalKnight
    RevanProdigalKnight almost 10 years
    Can you put an explanation of your code or at least some comments in your answer?
  • lukasz
    lukasz over 9 years
    way much proper than screwing everything with rotation.
  • Abin George
    Abin George about 9 years
    In the questions comments, Ohho has specified that, the cell heights are static. So i thought of this one. Thanks Alan for showing it.
  • Brennan
    Brennan almost 9 years
    One change I would make is to instead take the current content inset value and modify just the top value. You may need the bottom value set to another value besides 0 if you are showing a keyboard and have the offset set to allow the content at the bottom to show.
  • Brennan
    Brennan almost 9 years
    I've posted a new answer with a modern solution which works with autolayout and self sizing cells. Please review it and vote for it.
  • JoJo
    JoJo almost 9 years
    Less verbose way to do it: self.tableView.contentInset = UIEdgeInsetsMake(MAX(0.0, self.tableView.bounds.size.height - self.tableView.contentSize.height), 0, 0, 0); . Table view's content size is the size of all the cells.
  • Nitesh Borad
    Nitesh Borad over 7 years
    I liked your approach. But, I have one question. How can we get dynamic cell height using auto layout in collection view? We can do that in tableview using UITableViewAutomaticDimension.
  • MANIAK_dobrii
    MANIAK_dobrii over 7 years
    I'd suggest against autolayout inside UITableView/UICollectionView cells, but if you still need this you can do that in a number of ways, for collection view I've found that answer: stackoverflow.com/q/25895311/1032151 Usually, for UITableView you have a static "sizing cell" that you configure with your data and calculate height, with collection views it works differently, but with the layout I suggest, you may use the same concept.
  • HotJard
    HotJard almost 7 years
    Why to pass tableView and don't use it?
  • BallpointBen
    BallpointBen almost 7 years
    tableView.contentInset = contentInset;