ios - 如何将 UITableViewCell 定位在屏幕底部?

标签 ios cocoa-touch uitableview

一个UITableViewView中有一到三个UITableViewCell。有没有办法在 reloadData 之后始终将单元格定位在屏幕底部?

+----------------+     +----------------+     +----------------+
|                |     |                |     |                |
|                |     |                |     |                |
|                |     |                |     |                |
|                |     |                |     | +------------+ |
|                |     |                |     | |   cell 1   | |
|                |     |                |     | +------------+ |
|                |     | +------------+ |     | +------------+ |
|                |     | |   cell 1   | |     | |   cell 2   | |
|                |     | +------------+ |     | +------------+ |
| +------------+ |     | +------------+ |     | +------------+ |
| |   cell 1   | |     | |   cell 2   | |     | |   cell 3   | |
| +------------+ |     | +------------+ |     | +------------+ |
+----------------+     +----------------+     +----------------+

最佳答案

我已经创建了一个新的示例解决方案,因为以前的答案对于现代使用来说还不算过时。

最新技术使用自动布局和自动调整单元格大小,因此之前的答案将不再有效。我重新设计了解决方案以使用现代功能并创建了一个示例项目以放在 GitHub 上。

这段代码没有计算每行的高度,这会导致额外的工作,而是获取最后一行的框架,以便可以计算从顶部插入的内容。它利用了 TableView 已经在做的事情,因此不需要额外的工作。

此代码也仅设置顶部插图,以防为键盘或其他覆盖设置底部插图。

请在 GitHub 上报告任何错误或提交改进,我将更新此示例。

GitHub:https://github.com/brennanMKE/BottomTable

- (void)updateContentInsetForTableView:(UITableView *)tableView animated:(BOOL)animated {
    NSUInteger lastRow = [self tableView:tableView numberOfRowsInSection:0];
    NSUInteger lastIndex = lastRow > 0 ? lastRow - 1 : 0;

    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:lastIndex inSection:0];
    CGRect lastCellFrame = [self.tableView rectForRowAtIndexPath:lastIndexPath];

    // top inset = table view height - top position of last cell - last cell height
    CGFloat topInset = MAX(CGRectGetHeight(self.tableView.frame) - lastCellFrame.origin.y - CGRectGetHeight(lastCellFrame), 0);

    UIEdgeInsets contentInset = tableView.contentInset;
    contentInset.top = topInset;

    UIViewAnimationOptions options = UIViewAnimationOptionBeginFromCurrentState;
    [UIView animateWithDuration:animated ? 0.25 : 0.0 delay:0.0 options:options animations:^{
        tableView.contentInset = contentInset;
    } completion:^(BOOL finished) {
    }];
}

关于ios - 如何将 UITableViewCell 定位在屏幕底部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15285687/

相关文章:

ios - 从 String 到 Date() 转换的日期(转换后日期不正确)swift

ios - 如何在屏幕上为 UITabBar 设置动画并识别它通常所在的位置?

iphone - 我的应用程序的可读性

ios - 正确放置 reloadData

swift - 与委托(delegate)传递数据

ios - MonoTouch Mapkit 图像叠加

ios - 将选择器转发到 Swift 中的多个对象

ios - 如何仅为某些 View Controller 自定义 UINavigationBar

ios - 按需资源崩溃 - NSBundle 资源请求无法连接到其助手守护程序

ios - UITableView 单元格弹出菜单