views:

385

answers:

1

I have a table view which is many cases will only have one or two cells that don't fill the screen. In this case, I would like the cells to sit at the bottom, rather than the top. In other words they should "snap" to the bottom of the tableview.

I can force the table view to scroll them to the bottom like this:

  CGPoint bottomOffset = CGPointMake(0, [self.tableView contentSize].height - self.tableView.frame.size.height);
  [self.tableView setContentOffset:bottomOffset animated:NO];

However, this is only partially successful. First, it doesn't work if I put it in viewDidLoad or viewWillAppear, only in viewDidAppear, which means that the user sees the tableview with the cells at the top first, then they move to the bottom. Second, if they scroll the table view, when they let go it automatically "snaps" back up to the top.

Does anyone know how to change this behaviour?

+2  A: 

One option to consider is to resize the UITableView itself based on how many rows you will be displaying. Presuming that your UITableViewDelegate implements heightForRowAtIndexPath one can then set the height of the UITableView in a viewWillAppear method by multiplying the number of rows by the height of each row.

Something like this:

CGRect frame = [myTableView frame];

frame.size.height = [[myTableView dataSource] tableView: myTableView numberOfRowsInSection: 0] *
                    [[myTableView delegate] tableView: myTableView heightForRowAtIndexPath: [NSIndexPath indexPathForRow: 0 inSection: 0]];

[myTableView setFrame: frame];

This example assumes your table has one section and each row is the same height. Computing the size would have to get a little more complicated if multiple sections are involved or if different rows might be different heights.

Regardless of how the height is calculated the essence of the idea though is to just make the table itself shorter, no taller than the one or two rows that it is displaying, rather than trying to force it into behaving differently.

Terry Longrie