简体   繁体   中英

Keep tableview in same scroll position when adding cells with row animation

I have a tableview in my app which shows a list of calendar items. When a cell is selected I have set up functionality to show all calendar items in a time based tableview. To do this I insert blank cells to represent unused time.

The problem is that when I add cells the tableview scrolls to the top. I have tried setting the content offset after adding the cells but the row animation becomes buggy. I know i could just add new items to the array and call reloadData but this means I am missing out on animations.

Eg I have an hour long meeting at 9:00am and an hour long brunch at 11:00am. At first these are shown next to each other for easy reading. When I select the 11:00am cell:

  • 8 blank cells should be added above the 9:00am cell to represent the 8 empty hours before my meeting

  • a blank cell should be added between 9:00am and 11:00am to represent the empty hour between my meeting and brunch

  • 13 blank cells should be added after brunch to show the last 13 empty hours of the day.

When I started the 11:00am brunch cell was the second cell from the top. When the tableview expands I want this cell to remain in its position while the other cells animate around it. The meeting cell should move upwards out of the screen to make space for the blank cell below it.

I have tried to achieve this by creating an array of index paths to add blank cells and calling

[_tableView insertRowsAtIndexPaths:blankArray withRowAnimation:UITableViewRowAnimationFade]

I then calculate and set the content offset of the tableview to keep the brunch cell in the same position.

The problem is that when the content offset is set the cells are still animating from the top.This means that in order for the cells below the brunch to appear, they must first ping down the screen from the top of the tableview which causes flickering.Also the brunch and meeting cells do not part smoothly - the meeting cell just seems to disappear instead of sliding upward off screen.

I have considered writing my own tableview but it seems a difficult task.

Any solutions which would allow me to add cells with a row animation whilst keeping the selected cell in the same place would be helpful.

In iOS 6 and later, if you assign a value to a table view's restorationIdentifier property, it attempts to preserve the currently selected rows and the first visible row. GO to your main.storyboard select the tableView then click on the tableviews identity inspector You will see a section called Restoration ID put anything in there. BOOM MAGIC it works by it self.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM