在UITableView中垂直居中UITableViewCell

时间:2011-07-19 13:37:19

标签: iphone objective-c xamarin.ios

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

这是一个例子: enter image description here

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:3)

我会考虑在它上面放一个大的,透明的UITableViewCell(ala如何在gitHubby中使用用户的信息,但是没有数据)。

这就是480像素高的好处。你可以放入一些固定大小的东西,它一定会工作。

或者将\ n \ n \ n包含的部分标题放入其中,该标题也是不可见且透明的。

哦,对于Spy ++或运行iOS应用程序的东西:)

答案 2 :(得分:1)

斯威夫特3:

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        var contentHeight:CGFloat = 0.0
        for section in (0 ..< numberOfSections(in: tableView)) {
            for row in (0 ..< self.tableView(tableView, numberOfRowsInSection: section)) {
                let indexPath = NSIndexPath(row: row, section: section)
                contentHeight += self.tableView(tableView, heightForRowAt: indexPath as IndexPath)
            }
        }

        return (tableView.bounds.size.height - contentHeight)/2;
    }