Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 334
Josh Kahane Avatar asked Apr 25 '26 19:04

Josh Kahane


1 Answers

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.

like image 158
Pavan Avatar answered Apr 28 '26 17:04

Pavan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!