I am trying to find a better way to handle state recovery for a UICollectionView whose elements can be moved. My goal is to make sure that the last viewed item in the collection view is still displayed when the application restarts, even if the items are moved. For example, element A is in the cell with index 3, when the application was killed, and when the application restarts, if the model reports that element A should be displayed with index 4, I want the collection view to initialize the offset of the cell with index 4.
I thought that implementing the UIDataSourceModelAssociation protocol in my UICollectionViewDataSource class UICollectionViewDataSource take care of this for me, as the documentation says:
In the classes[UITableView and UICollectionView] use the methods of this protocol to ensure that the same data objects (and not just the same row indices) are scrolled into the view and selected.
However, I noticed that the implementation of this protocol correctly affects the indexPath of selected cells during recovery (which is not important for my application), but this does not affect the scroll position. The scroll position (contentOffset of the collection view) is always restored exactly where it was when the application was killed and not affected by the UICollectionViewDataSource.
I have a workaround that looks like this. This is basically the same template as the model matching protocol, but I have to do it manually:
override func encodeRestorableStateWithCoder(coder: NSCoder) { let identifier = determineIdOfCurrentlyVisibleCell() coder.encodeObject(identifier, forKey: "visibleCellIdentifier") } override func decodeRestorableStateWithCoder(coder: NSCoder) { if let identifier = coder.decodeObjectForKey("visibleCellIdentifier") as? String { if let indexPath = model.indexPathForIdentifier(identifier) { collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredVertically, animated: false) } } }
I misunderstood the use of UIDataSourceModelAssociation? Is there a mistake? Is there a more elegant or proper way to make this work?
source share