Josh Kahane
Josh Kahane

Reputation: 17169

UICollectionView Selection Lost When Scrolling

I have a simple UICollectionView up and running and have it so you can select a cell then save your selection. But guess what? I have a problem!

After scrolling the selected cell off-screen and back on, it looses its selection. Pretty simple at the surface. How can I stop this?

Is this something to do with cell reuse? Here is my code:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"AircraftConfigurationCell";
    SLAircraftConfigurationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    //Customise cell...

    return cell;
}

Upvotes: 3

Views: 1867

Answers (1)

Pavan
Pavan

Reputation: 18548

Do you have a datasource which is formed possibly from an array containing data models?

If so then you're off to a great start and can sort out this selection intermittent behaviour in no time!

In your data model .h file create a property like so property (nonatomic, retain) BOOL selectedState; and in the .m file initialise the selectedState to FALSE in your data object's init method.

Once that's done in your UICollectionView's didSelect method, set the dataObject's selectedState to YES that is associated to that cell/item index.

Then finally in your cellForItemAtIndexPath method, ensure you do an if check on the dataModel instance that youre going to set the cellItem with for the selectedState property. If its set to `NO' set the selectionStyle to none, otherwise set it to yes.

I used to have your problem before where selection would be lost when scrolling, but now its being managed and the result is persistent.

Upvotes: 1

Related Questions