收录日期:2020/10/31 21:50:03 时间:2010-09-14 02:24:57 标签:iphone,uitableview

Suppose I have a table view, and I want to implement something like this:

  • The table view contains n cells by default.
  • New cells will be added at the top(head) of the table view.
  • The data source of the table view is a mutable array.

The problem is when I use [tableview reloadData], the new data is always shown at the top of the tableview, but what I want is remain the old visible cells at the old position, means no refresh after reload data. I had tried some solutions, and I found out that if I added new cells at the tail, and update the tableview, the old visible cells will remain old position without any extra effort. But I don't know how to remain the old visible cells at the old position if I add the new cells at the top.

As a reference, I think the official Twitter app for iPhone just implemented what I want in the time line view, but I don't know how to archive it.

Guys, have any idea?

Thanks a lot.

-Tonny Xu

[Update] It's a little bit hard to describe what I want in text. I added some pictures.

As the picture shows[the link is below], the default cells is started from section California, I want to added 3 new cells before "Brea", what I want is after I added "New cell 1,2,3", the cell "Brea" is still remain the position where it was. In another word, the new cells 1,2,3 are not visible after updated.

Sorry, because I don't have enough reputation to use image, please visit this url http://i.stack.imgur.com/S9jJl.png

I had figured out how to implement this, hope this can help somebody else who wants the same effect.

The point is that UITableView is a subclass of UIScrollView. Thus, UITableView has all the properties of UIScrollView, especially one will work for this: UITableView.contentOffset, this can also be animated using [UITableView setContentOffset:animated:].

To archive the same effect as Twitter for iPhone official app, we need to know every time how much offset is added or deleted. Remember the former offset and set the offset +/- delta offset without animation.

Done.

Just answered a similar question with code snippets here

Keep uitableview static when inserting rows at the top

Basically:

  • Save the scroll offset where you would have called beginUpdate:.
  • In place of calls to InsertCell you add the cell's height to the saved offset.
  • Where you would have called endUpdate:, call reloadData, then scroll by the saved offset with NO animation.