Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center UITableViewCell in UITableView

How would you go about centering a cell vertically in a UITableViewCell when there's only one or two cells? Apple does this quite often in their apps, for example in the Settings app, when editing the date.

Here's an example: enter image description here

like image 544
Eduardo Scoz Avatar asked Dec 02 '22 01:12

Eduardo Scoz


2 Answers

I went with the header strategy, and dynamically calculate the content height to center all content in the table. The advantage of this is that it will work with any table content or view size:

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    CGFloat contentHeight = 0.0;
    for (int section = 0; section < [self numberOfSectionsInTableView: tableView]; section++) {
        for (int row = 0; row < [self tableView: tableView numberOfRowsInSection: section]; row++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow: row inSection: section];
            contentHeight += [self tableView: tableView heightForRowAtIndexPath: indexPath];
        }
    }
    return (tableView.bounds.size.height - contentHeight)/2;
}


- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        UIView *view = [[UIView alloc] initWithFrame: CGRectZero];
        view.backgroundColor = [UIColor clearColor];
        return view;
}
like image 80
Chris Garrett Avatar answered Dec 28 '22 18:12

Chris Garrett


I'd consider putting a large, transparent UITableViewCell above it (ala how you do it in gitHubby with the user's info, but with no data).

thats the benefit of have 480 pixels high. you can put something in, fixed size, and it'll JUST WORK.

Or put a \n\n\n containing section header in, which is also invisible and transparent.

oh for Spy++ or something for running iOS apps :)

like image 24
Nic Wise Avatar answered Dec 28 '22 18:12

Nic Wise