简体   繁体   中英

iOS Swift: Save/restore scroll position when recycling cells

I have a custom UITableViewCell that contains a scrollview. How would I go about saving and restoring the scroll position for each cell? I don't need the position to be saved across sessions, just as I scroll up and down I would like the positions to be preserved.

The cell can be reused as you scroll around so you can't save it in the cell object - typically there are ever only n+1 cells in existence where n is the number of cells that can be displayed at one time.

If you really need to maintain state of cells then that is properly a function of the data source, so record state for each object represented by the table or collection view.

If it doesn't need to be persistent you can just maintain a dictionary of state objects (or simple numbers if all you need is a scroll position). Let each cell refer to the table or collection view's data source as a delegate using a protocol you define. When a cell's state changes and you need to save that then the cell should report state to its delegate and the delegate maintains that state with the index path as key. Next time you see that index path in cellForItemAtIndexPath you set the cell back to the state it last reported.

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