Using UICollectionView scrollToItemAtIndexPath to return to last selected cell
I have UICollectionView for the user to select images from a grid. Once a cell is selected, the view controller is released, including the UICollectionView.
I'd like to remember where the user was last time they used the UICollectionView and automatically scroll to that location when the view controller is loaded again.
The problem I'm encountering is when this can be done. I'm assuming I need to wait until the UICollectionView has been fully loaded before executing scrollToItemAtIndexPath:atScrollPosition:animated:
.
What's the preferred way to determine when the view controller and UICollectionView are fully laid out?
I spent some time exploring solutions. @Leo, I was not able to scroll in viewDidLoad
. However, I was able to achieve good results keeping track of the state of the view life cycle.
I created a constant to remember the content offset. I used a constant so it would retain it's value between loads of the VC. I also created a property to flag when it was okay to scroll:
static CGPoint kLastContentOffset;
@property (nonatomic) BOOL autoScroll;
@property (weak, nonatomic) IBOutlet UICollectionView *collection;
The life cycle code I used:
- (void)viewDidLoad
{
[super viewDidLoad];
self.autoScroll = NO; // before CollectionView laid out
}
- (void)viewDidDisappear:(BOOL)animated
{
kLastContentOffset = self.collection.contentOffset;
[super viewDidDisappear:animated];
}
- (void)viewDidLayoutSubviews
{
if (self.autoScroll) { // after CollectionView laid out
self.autoScroll = NO; // don't autoScroll this instantiation of the VC again
if (kLastContentOffset.y) {
[self.collection setContentOffset:kLastContentOffset];
}
}
During the layout of the collectionView I set the flag indicating that the next viewDidLayoutSubviews
should auto scroll:
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
{
self.autoScroll = YES;
// return count here
}
The important part was saving the content offset when my view disappeared. The constant is not remembered between launches of the application which what I wanted and the reason for not saving it in preferences.
Seems like there has to be a more elegant solution but this works well.
链接地址: http://www.djcxy.com/p/91640.html