如何垂直对齐(居中)UITableView的内容?

Xch*_*ord 12 xcode objective-c storyboard uitableview ios

我想中心的我的内容UITableView包含headerViewfooterView在故事板创建,UITableViewCell秒.我怎样才能做到这一点?

这是我试图解决我的问题,但这不起作用.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    CGFloat height = self.tableView.frameHeight - self.navigationController.navigationBar.frameHeight - [UIApplication sharedApplication].statusBarFrame.size.height - (self.rowCount * self.rowHeight);
    self.tableView.tableHeaderView.frameHeight = height / 2.0;
}
Run Code Online (Sandbox Code Playgroud)

所以我将navigationBar&statusBar的高度和单元格的高度减去tableView的高度,以获得空白区域的高度.现在我得到了空白区域的高度,我将其分为2为页脚和标题的视图.

Pip*_*iks 28

viewWillAppeardidRotateFromInterfaceOrientation函数中:

CGFloat headerHeight = (self.view.frame.size.height - (ROW_HEIGHT * [self.tableView numberOfRowsInSection:0]))) / 2;

self.tableView.contentInset = UIEdgeInsetsMake(headerHeight, 0, -headerHeight, 0);
Run Code Online (Sandbox Code Playgroud)

这将解决您的问题.

编辑

viewWillLayoutSubviews中调用updateTableViewContentInset函数,并在每次reloadData之后调用:

Ojective-C

- (void)updateTableViewContentInset {
    CGFloat viewHeight = self.view.frame.size.height;
    CGFloat tableViewContentHeight = self.tableView.contentSize.height;
    CGFloat marginHeight = (viewHeight - tableViewContentHeight) / 2.0;

    self.tableView.contentInset = UIEdgeInsetsMake(marginHeight, 0, -marginHeight, 0);
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特4

func updateTableViewContentInset() {
    let viewHeight: CGFloat = view.frame.size.height
    let tableViewContentHeight: CGFloat = tableView.contentSize.height
    let marginHeight: CGFloat = (viewHeight - tableViewContentHeight) / 2.0

    self.tableView.contentInset = UIEdgeInsets(top: marginHeight, left: 0, bottom:  -marginHeight, right: 0)
}
Run Code Online (Sandbox Code Playgroud)

  • 您的解决方案非常优雅和干净,在您拥有动态数量的单元格的情况下失败.如果您的表格中有太多单元格,则无法正确显示.所以下面将解决这个问题:`headerHeight = MAX(0,headerHeight);` (4认同)

Axe*_*min 7

覆盖viewDidLayoutSubviewstableView frame并将其与其contentSize进行比较以设置contentInset。在Swift 4中:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    let tableViewHeight = self.tableView.frame.height
    let contentHeight = self.tableView.contentSize.height

    let centeringInset = (tableViewHeight - contentHeight) / 2.0
    let topInset = max(centeringInset, 0.0)

    self.tableView.contentInset = UIEdgeInsets(top: topInset, left: 0.0, bottom: 0.0, right: 0.0)
}
Run Code Online (Sandbox Code Playgroud)

这适用于自调整大小的表格视图单元格

  • 在“viewDidLayoutSubviews”中,“self.tableView.contentSize.height”是根据“estimatedRowHeight”计算的,而不是实际调整大小的单元格。将其移至“viewDidAppear”即可解决问题。但不确定这是否是一个好的解决方案。 (2认同)