在UITableView中垂直居中UITableViewCell

Edu*_*coz 4 iphone objective-c xamarin.ios

当只有一个或两个单元格时,你会如何在UITableViewCell中垂直居中?Apple在编辑日期时会在应用中经常这样做,例如在"设置"应用中.

这是一个例子: 在此输入图像描述

Chr*_*ett 14

我使用了标题策略,并动态计算内容高度以使表中的所有内容居中.这样做的好处是它可以处理任何表格内容或视图大小:

- (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;
}
Run Code Online (Sandbox Code Playgroud)