Reputation: 4138
I have a collectionView that will only display three cells. Each cell is of the same type of custom collectionViewCell that I've set up in storyboard. I only want each cell instantiated once and only once; not reused.
How can I return cells from cellForItemAtIndexPath: datasource method that aren't reused? Is it possible to do this?
Upvotes: 1
Views: 6520
Reputation: 2810
UICollectionViewCell
doesn't mean you're getting rid of the previous ones that are no longer on the screen.UICollectionView
based on the UICollectionViewLayout
you're needing.UIScrollView
that reuses them instead of allocating memory for every cell that will eventually be appearing.UICollectionViewDataSource
Protocols, your collection view repopulates the cell that just left the screen and puts it below, or above, the displayed list to be "reused" instead of causing memory problems.Collection Views are incredibly efficient and I would recommend utilizing their built in Memory saving dequeuereusablecellwithidentifier
.
You would get the result you're wanting by putting the Necessary Data you'll need within the cells (possibly making a subclass of the UICollectionViewCell
if needed) inside a NSArray
.
You'll access each object (1 - 100 in our example) using the cellForItemAtIndexPath
and as your scroll, the basic principle of reusing the cells will display the NSArray objects that are needed to be displayed.
I'm hoping this makes sense and it helps you solve your problem!
Upvotes: 3
Reputation: 5047
Use properties:
@property (nonatomic, strong) UICollectionViewCell *firstCell;
@property (nonatomic, strong) UICollectionViewCell *secondCell;
@property (nonatomic, strong) UICollectionViewCell *thirdCell;
In viewDidLoad you can create it:
self.firstCell = [[UICollectionViewCell alloc] init];
// Do you need...
And your delegate methods, look like:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.row) {
case 0:
return self.firstCell;
break;
case 1:
return self.secondCell;
break;
case 2:
return self.thirdCell;
break;
default:
return nil;
break;
}
}
Upvotes: -2