在顶部插入行时保持 uitableview 静态 [英] Keep uitableview static when inserting rows at the top

查看:18
本文介绍了在顶部插入行时保持 uitableview 静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 tableView,我要在顶部插入行.

I have a tableView that I'm inserting rows into at the top.

在执行此操作时,我希望当前视图完全静止,因此只有向上滚动时才会显示行.

Whilst I'm doing this I want the current view to stay completely still, so the rows only appear if you scroll back up.

我已经尝试保存底层 UIScrollview 的当前位置并在插入行后重置位置,但这会导致上下抖动,尽管它最终会回到同一个位置.

I've tried saving the current position of the underlying UIScrollview and resetting the position after the rows have been inserted but this results in a judder, up and down, although it does end up back in the same place.

有什么好的方法可以实现吗?

Is there a good way of achieving this ?

更新:我使用beginUpdate,然后insertRowsAtIndexPath,endUpdates.没有 reloadData 调用.

Update: I am using beginUpdate, then insertRowsAtIndexPath, endUpdates. There is no reloadData call.

scrollToRowAtIndexPath 跳转到当前单元格的顶部(添加行之前保存).

scrollToRowAtIndexPath jumps to the top of the current cell (saved before adding rows).

我尝试过的另一种方法,它以完全正确的速度结束,但有点颤抖.

The other approach I tried, which ends up in exactly the right pace, but with a judder is.

save tableView currentOffset. (Underlying scrollView method)
Add rows (beginUpdates,insert...,endUpdates) 
reloadData ( to force a recalulation of the scrollview size )
Recalculate the correct new offset from the bottom of the scrollview
setContentOffset (Underlying scrollview method)

问题是 reloadData 导致 scrollview/tableview 开始短暂滚动,然后 setContentOffset 将其返回到正确的位置.

Trouble is the reloadData causes the scrollview/tableview to start scrolling briefly, then the setContentOffset returns it to the correct place.

有没有办法让 tableView 在不开始显示的情况下计算出它的新大小?

Is there a way of getting a tableView to work out it's new size without starting display ?

将整个内容包装在 beginAnimation commitAnimation 中也无济于事.

Wrapping the whole thing in a beginAnimation commitAnimation doesn't help much either.

更新 2:这显然是可以做到的 - 当您下拉更新时,请查看官方推特应用.

Update 2: This can clearly be done - see the offical twitter app for one when you pull down for updates.

推荐答案

真的没必要把所有的行高都加起来,重新加载表格后的新 contentSize 已经代表了这一点.所以你所要做的就是计算 contentSize 高度的 delta 并将其添加到当前偏移量中.

There's really no need to sum up all rows height, the new contentSize after reloading the table is already representing that. So all you have to do is calculate the delta of contentSize height and add it to the current offset.

    ...
    CGSize beforeContentSize = self.tableView.contentSize;
    [self.tableView reloadData];
    CGSize afterContentSize = self.tableView.contentSize;

    CGPoint afterContentOffset = self.tableView.contentOffset;
    CGPoint newContentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);
    self.tableView.contentOffset = newContentOffset;
    ...

这篇关于在顶部插入行时保持 uitableview 静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆