如何将UITableViewCell对齐到UITableView的底部?

Pwn*_*ner 4 cocoa-touch uitableview ios

当您插入第一个UITableViewCellinsertRowsAtIndexPaths:withRowAnimation:,它通常出现在UITableView.在Periscope应用程序中,相反的情况发生 - 第一个插入的单元格是底部对齐的.当推入新细胞时,旧细胞会在表格中向上移动.这是如何实现的?

在此输入图像描述

Aar*_*man 21

如果你对我在Periscope iOS应用程序中的表现感兴趣,它实际上非常简单......

TL; DR; 添加一个透明的表头标题视图,其高度等于表视图框架的高度.然后,在向表中添加单元格时,只需为表格视图的内容偏移设置动画.

为表格视图提供标题视图:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectZero];
    headerView.userInteractionEnabled = NO; // all touches within this space must go through to the video layer

    return headerView;   // empty header above chat, so messages flow in from bottom
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.tableView.frame.size.height;            // empty header above chat, so messages flow in from bottom
}
Run Code Online (Sandbox Code Playgroud)

向表中添加数据(在我的例子中,消息被添加到名为_messages的数组中.然后我在UITableViewController上调用reloadData).然后调用此方法为单元格设置动画:

- (void)scrollTableToBottom
{
    if (!self.isViewLoaded || _messages.count == 0)
        return;

    CGFloat offsetY = self.tableView.contentSize.height - self.tableView.frame.size.height + self.tableView.contentInset.bottom;

    [UIView animateWithDuration:0.33
            delay:0
            options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionAllowUserInteraction
            animations:^{
                [self.tableView setContentOffset:CGPointMake(0, offsetY) animated:NO];
            }
            completion:nil];
}
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.我发现这是一种非常便宜/简单的模拟固定在底部的细胞的方法.我知道有些人提到颠倒翻转桌子,但这对我来说似乎很疯狂.:-)